본문 바로가기

IOS Swift

Swift 텍스트필드 키보드 내리기

UIView 안에 있는 텍스트필드를 처리하려할 때

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

 

UIScrollView 안에 있는 텍스트필드 키보드를 처리하려 할 때

class UIViewController {

	override func viewDidLoad() {
		super.viewDidLoad()
		configureUI()
    }
    
	private func configureUI() {

		let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.touch))
		recognizer.numberOfTapsRequired = 1
		recognizer.numberOfTouchesRequired = 1
        
		scrollView.addGestureRecognizer(recognizer)
 	}
    
	@objc func touch() {
		self.view.endEditing(true)
	}
}

 

스크롤뷰, 테이블뷰 등에서는 이렇게 제스처를 추가해줘야하는 이유는

스크롤뷰에서 스크롤을 처리해야하기 때문에

터치에 대한 이벤트를 스크롤뷰가 처리해버려 상위의 UIViewController의 UIView까지 이벤트가 전달되지 못하기 때문입니다.

더보기

If the value of this property is YES , scrolling is enabled, and if it is NO , scrolling is disabled. The default is YES.

When scrolling is disabled, the scroll view does not accept touch events; it forwards them up the responder chain. 스크롤이 비활성화되면, 그 스크롤은 터치 스크롤을 받지 않고 responder chain 앞으로 터치 이벤트를 보낸다.!

애플 공식문서 - https://developer.apple.com/documentation/uikit/uiscrollview/1619395-scrollenabled

 

그래서 스크롤뷰에다가 터치시 키보드가 내려가는 제스처를 추가해주면 원하는대로 동작합니다!

 

분명 다른 여러 앱에서 키보드 올리고 내릴 때 모든 화면마다 아래와 같은 공통된 textfield accessory view가 있어서 위의코드를 뷰컨트롤러마다 작성하진 않을 것 같다는 생각이 들어서 좀 더 찾아보다가 라이브러리 발견!

텍스트필드 Accessory View

이 라이브러리 쓰면 AppDelegate에서 한줄만 적어주면 키보드 때문에 뒤에 화면이 가려지는 거랑 Accessory View까지 한방에 해결할 수 있더군요. Good!

키보드 올리고 내리는 라이브러리 : https://github.com/hackiftekhar/IQKeyboardManager

 

반응형