[iOS] endEditing 기능 적용하기/화면 터치해 키보드 내리기

doooly·2023년 8월 28일
0

iOS

목록 보기
4/8

실제 디바이스에서 시뮬레이터를 돌릴 때, textfield에 입력을 마친 후에도 키보드가 내려가지 않아 앱의 기능을 제대로 실행하지 못하는 경우가 생긴다.
이를 해결하기 위해, editing일 때 view의 다른 부분을 tap하면 edit을 종료할 수 있도록 endEditing함수를 사용해보았다.

extension UIViewController {
    func handleEditFunc(){
        let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
      }
      
      @objc func handleTap() {
          self.view.endEditing(true)
      }
}

1. UITapGestureRecognizer type인 상수를 생성


2. 상수의 cancelsTouchesInView 기능을 false로 설정

https://developer.apple.com/documentation/uikit/uigesturerecognizer/1624218-cancelstouchesinview

When this property is true (the default) and the gesture recognizer recognizes its gesture, the touches of that gesture that are pending aren’t delivered to the view and previously delivered touches are canceled through a touchesCancelled(_:with:) message sent to the view. If a gesture recognizer doesn’t recognize its gesture or if the value of this property is false, the view receives all touches in the multi-touch sequence.



'제스처가 인식될 때 터치가 뷰로 전달되는지 여부를 결정하는 부울 값'으로

이 속성이 참(기본값)이고 제스처 인식기가 제스처를 인식하면, 보류 중인 제스처의 터치는 뷰에 전달되지 않으며 이전에 전달된 터치는 뷰로 전송된 touchesCancelled(_:with:) 메시지를 통해 취소됩니다.
제스처 인식기가 제스처를 인식하지 못하거나 이 속성의 값이 거짓인 경우, 뷰는 멀티 터치 시퀀스의 모든 터치를 수신합니다.



3. view.addGestureRecognizer

tapGesture을 사용할 view에 위에서 만든 UITapGestureRecognizer상수를 addGestureRecognizer을 통해 붙입니다.


4. action함수에 endEditing함수 사용

https://developer.apple.com/documentation/uikit/uiview/1619630-endediting
이 방법은 현재 첫 번째 응답자인 텍스트 필드에 대한 현재 뷰와 하위 뷰 계층 구조를 살펴봅니다. 하나를 찾으면, 그 텍스트 필드에 첫 번째 응답자로 사임하도록 요청합니다. 강제 매개 변수가 true로 설정되면, 텍스트 필드는 절대 묻지 않습니다. 강제로 사임해야 합니다.


view를 tap했을 때 실행되는 함수를 생성합니다.
view.endEditing을 true로 설정해 editingmode를 종료합니다.
이를 통해 키보드를 강제로 내릴 수 있습니다.


0개의 댓글