아이폰

Swift 키보드 Show/Hide 이벤트, 화면 밖 터치로 내리기

SourceTree 2021. 11. 20. 08:45
반응형

키보드 보임/사라짐 이벤트

  • 키보드가 보일때 화면을 위로 100만큼 올려 UITextField가 키보드에 가리는걸 방지한다.
//등록
NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillShown(_:)),name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillBeHidden(_:)),name: UIResponder.keyboardWillHideNotification, object: nil)

//키보드가 보일때 화면을 위로 100만큼 올린다.
@objc func keyboardWillShown(_ notificiation: NSNotification) {
  self.view.frame = CGRect(x: 0, y: -100, width: self.view.frame.size.width, height: self.view.frame.size.height)
}
 
//키보드가 사라질때 화면을 다시 원복한다.
@objc func keyboardWillBeHidden(_ notification: NSNotification) {
  self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
}

 

화면 밖 터치해서 키보드 내리기(아래 func을 추가한다)

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