swift之防止键盘遮挡输入框

1、先添加约束,这里用图上注册按钮到view底部的约束

swift之防止键盘遮挡输入框_第1张图片
7833BDEA-6C3F-4B50-9B43-067F04503BA7.png

2、实现代码

@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()
    
    NSNotificationCenter.defaultCenter().addObserver(self,
        selector: "keyboardWillChange:",
        name: UIKeyboardWillChangeFrameNotification, object: nil)
}

/**
 *键盘改变
 */
func keyboardWillChange(notification: NSNotification) {
    if let userInfo = notification.userInfo,
        value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
        duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
        curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt {
            
            let frame = value.CGRectValue()
            var intersection = CGRectIntersection(frame, self.view.frame)
            
            //当键盘消失,让view回归原始位置
            if intersection.height == 0.0 {
                intersection = CGRect(x: intersection.origin.x, y: intersection.origin.y, width: intersection.width, height: 100)
            }
            UIView.animateWithDuration(duration, delay: 0.0,
                options: UIViewAnimationOptions(rawValue: curve), animations: {
                    _ in
                    //改变下约束
                    self.bottomConstraint.constant = CGRectGetHeight(intersection)
                    self.view.layoutIfNeeded()
                }, completion: nil)
    }
}
swift之防止键盘遮挡输入框_第2张图片
FB6AA06E-FBDC-4253-B41A-DA679441CA8A.png
swift之防止键盘遮挡输入框_第3张图片
C45957C1-AE5D-4BB1-B0D6-B98B9F847345.png

你可能感兴趣的:(swift之防止键盘遮挡输入框)