swift3 键盘通知事件

前端之家收集整理的这篇文章主要介绍了swift3 键盘通知事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
class MyViewController: UIViewController {

// This constraint ties an element at zero points from the bottom layout guide
@IBOutlet var keyboardHeightLayoutConstraint: NSLayoutConstraint?

override func viewDidLoad() {
    super.viewDidLoad()
    // Note that SO highlighting makes the new selector Syntax (#selector()) look
    // like a comment but it isn't one
    NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardNotification(notification:)),name: NSNotification.Name.UIKeyboardWillChangeFrame,object: nil)
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

@objc func keyboardNotification(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
        let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
        let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
        let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
        if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height {
            self.keyboardHeightLayoutConstraint?.constant = 0.0
        } else {
            self.keyboardHeightLayoutConstraint?.constant = endFrame?.size.height ?? 0.0
        }
        UIView.animate(withDuration: duration,delay: TimeInterval(0),options: animationCurve,animations: { self.view.layoutIfNeeded() },completion: nil)
    }
}
原文链接:https://www.f2er.com/swift/321257.html

猜你在找的Swift相关文章