swift 监听键盘显示与消失

公司需求做个类似于评论框的输入框

1.收到需求第一时间想到的效果是键盘弹出(显示)出来以后,输入框自动随着键盘向上移动,底部一直浮动在键盘顶部。键盘消失输入框隐藏并且释放第一响应
2.键盘弹出和消失明显是两个状态,那么这两个状态对应的名字为:
1)UIResponder.keyboardWillShowNotification 键盘将要显示
2)UIResponder.keyboardWillHideNotification 键盘将要隐藏
那么怎么获取这两个状态呢?那就要对这两个状态进行观察者监听

 //监听键盘通知
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillShow(_:)),
                                               name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillhide(_:)),
                                               name: UIResponder.keyboardWillHideNotification, object: nil)
    //键盘改变
    @objc func keyboardWillShow(_ sender: NSNotification) {
        //获取键盘的frame
        guard let keyboardFrame = (sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {
            return
        }
        print("=======\(keyboardFrame)")
        //获取动画执行的时间
        var duration = sender.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
        if duration == nil { duration = 0.25 }

        UIView.animate(withDuration: duration!, delay: 0, options: .allowAnimatedContent, animations: {
            self.bottomConstraint?.update(offset: -keyboardFrame.height)
            self.layoutIfNeeded()
        }, completion: nil)

    }

    @objc func keyboardWillhide(_ sender: NSNotification) {
        //        dissmiss()
        UIView.animate(withDuration: 0.1, animations: {
            self.bottomConstraint?.update(offset: 0)
            self.layoutIfNeeded()
        })
    }
        toolView.snp.makeConstraints({ (make) in
            bottomConstraint =  make.bottom.equalToSuperview().constraint
            make.left.right.equalToSuperview()
            make.height.equalTo(SKScale(float: 244))
        })

注意:如果写在Controller里的时候一定要在deinit 内对观察者进行移除

   deinit {
         NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
         NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)

    }

你可能感兴趣的:(iOS,--,键盘,ios,swift)