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

2017-03-24  本文已影响0人  figure_ai
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<UITouch>, 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的父视图不是覆盖这个界面的视图的话,计算出来的结果是有误差的。如果你有更好的封装方法,谢谢分享,毕竟如果每次要实现自适应的时候都要写一次代码,那无疑太麻烦

上一篇下一篇

猜你喜欢

热点阅读