swift3.0-键盘自适应高度的简单封装

  • 代码如下,将键盘的监听以及自适应高度的实现添加到UITextField的扩展中使用的时候,只需一行代码即可搞定
class ViewController: UIViewController {
    
    let field = UITextField.init()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        field.placeholder = "请输入文字"
        field.borderStyle = .line
        field.frame = CGRect(x: 10, y: UIScreen.main.bounds.size.height - 140, width: UIScreen.main.bounds.size.width - 20, height: 40)
        //注册键盘监听
        field.registNotification()
        view.addSubview(field)
    }
    
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    deinit {
        field.removeObserver()
    }
}
  • 以下是实现自适应的代码
extension UITextField {
    ///注册通知
    func registNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(willShow(obj:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(willHide(obj:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
    }
    
    func willShow(obj: Notification) {
        print("键盘弹出")
        //获取键盘高
        let info = obj.userInfo
        let userInfo = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue)
        let rect = userInfo.cgRectValue
        let keyH = rect.size.height
        //计算输入框到底部的距离
        let fieldY = UIScreen.main.bounds.size.height - self.frame.maxY
        //判断是否遮住键盘
        print(fieldY)
        if keyH > fieldY {
            self.superview?.frame.origin.y = -(keyH - fieldY)
        }
    }
    func willHide(obj: Notification) {
        print("键盘隐藏")
        UIView.animate(withDuration: 5) {
            self.superview?.frame.origin.y = 0
        }
    }
    ///移除通知
    func removeObserver() {
        NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil)
    }
}
  • 运行结果
键盘自适应运行结果.gif

当然,这样子封装起来的话还是有问题,如果textField的父视图不是覆盖这个界面的视图的话,计算出来的结果是有误差的。如果你有更好的封装方法,谢谢分享,毕竟如果每次要实现自适应的时候都要写一次代码,那无疑太麻烦

你可能感兴趣的:(swift3.0-键盘自适应高度的简单封装)