Swift3.0 监控键盘的弹出与收回

1.注册/移除通知

 override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

 deinit {
  //移除通知
  NotificationCenter.default.removeObserver(self)
    }

2.实现通知中的方法

 //键盘的出现
    func keyBoardWillShow(_ notification: Notification){
        //获取userInfo
        let kbInfo = notification.userInfo
        //获取键盘的size
        let kbRect = (kbInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        //键盘的y偏移量
        let changeY = kbRect.origin.y - SCREEN_HEIGHT
        //键盘弹出的时间
        let duration = kbInfo?[UIKeyboardAnimationDurationUserInfoKey] as! Double

       //界面偏移动画
        UIView.animate(withDuration: duration) {

            self.aTableView.transform = CGAffineTransform(translationX: 0, y: changeY)
        }
    }

    //键盘的隐藏
    func keyBoardWillHide(_ notification: Notification){

        let kbInfo = notification.userInfo
        let kbRect = (kbInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let changeY = kbRect.origin.y
        let duration = kbInfo?[UIKeyboardAnimationDurationUserInfoKey] as! Double

        UIView.animate(withDuration: duration) {
           self.tableViewConstraint.update(inset: 0)
        }
    }

你可能感兴趣的:(UIKeyBoard)