티스토리 뷰

키보드를 내리고 싶을 때

두가지 방법이 있다.

  • 키보드의 리턴키를 눌러서 끝내기
    키보드의 리턴키를 누르면 textFieldShouldReturn(_:) 델리게이트 메소드가 호출된다.
    이 메소드 내에서 textField.resignFirstResponder() 메소드를 호출하면 된다.

      func textFieldShouldReturn(_ textField: UITextField) -> Bool {
          textField.resignFirstResponder()
          return true
      }
  • 화면 다른 곳을 터치시켜서 끝내기
    UIViewController의 touchesBegan(_:, with:) 메소드를 오버라이드하고 내부에서 view.endEdting(_:) 메소드를 호출한다.

      override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
          self.view.endEditing(true)
      }

UITextFieldDelegate 메소드 호출 순서(Keyboard-Related Notification은 생략)

  1. textField가 firstResponder가 되기 전에, textFieldShouldBeginEditing(_:) 메소드를 호출한다
  2. textField가 firstResponder가 된다.
  3. textFieldDidBeginEditing(_:) 메소드를 호출한다
  4. 1) text가 바뀔 때 마다, textField(_:shouldChangeCharactersIn:replacementString:) 메소드를 호출한다. 이 메소드는 Bool 타입을 리턴하여 편집 유무를 확인한다. 이때 shouldChangeCharactersIn 인자는 편집될 범위를 나타내고, replacementString은 대체할 문자를 나타낸다.

주의할 점은 이 메소드가 호출된 시점에서는 아직 textField.text? 가 갱신되지 않았다는 점이다.
2) built-in인 클리어 버튼을 클릭할 때마다
textFieldShouldClear(_:) 메소드를 호출한다. 역시 Bool을 반환한다.
3) 키보드의 return 키, 확인키, done 키 등을 유저가 누를 때 마다
textFieldShouldReturn(_:) 메소드를 호출한다. 역시 Bool 타입을 반환하며 가능 여부를 delegate에게 묻는다.
5. textField가 firstResponder를 resign하기 직전에, textFieldShouldEndEditing(_:) 메소드를 호출한다. Bool 타입을 반환한다. 현재 textField에 입력된 텍스트의 validation을 검증할 때 주로 사용한다.
6. textField가 firstResponder를 resign한다.
7. textFieldDidEndEditing(_:) 메소드를 호출한다.

출처

https://developer.apple.com/documentation/uikit/uitextfielddelegate

댓글