iOS-键盘弹出或隐藏时调整输入框的位置

要达到自动调整的目标需要监听 keyboardWillShowNotification 跟 keyboardWillHideNotification, 同时需要实现点击其它地方时,通知隐藏键盘的事件

ViewController.swift
viewDidLoad{
  NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
  NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
  
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(self.dismissKeyboard))
  view.addGestureRecognizer(tap)  
}
@objc func dismissKeyboard() {
  view.endEditing(true)
}
@objc func keyboardWillShow(notification: NSNotification) {
  if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
    if self.view.frame.origin.y == 0 {
      self.view.frame.origin.y -= keyboardSize.height
    }
  }
}
 
@objc func keyboardWillHide(notification: NSNotification) {
  if ((notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue)!= nil {
    if self.view.frame.origin.y != 0 {
      self.view.frame.origin.y = 0
    }
  }
}
 
PS: 如果模拟器没有虚拟键盘 Hardware ➤ Keyboard ➤ Toggle Software Keyboard 或 Command + K
 

 

posted @ 2020-05-06 15:52  modentime  阅读(638)  评论(0编辑  收藏  举报