IOS输入框随键盘抬起防遮挡

上代码

// 输入框距离底部距离的约束
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

// 注册事件,获取键盘变化状态(包括键盘自身的输入法切换引起的高度变化)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: .UIKeyboardWillChangeFrame, object: nil)
    
// 反注册事件    
deinit {
  NotificationCenter.default.removeObserver(self)
}

// 随着键盘弹起,处理autolayout的约束并且刷新UI
func keyboardWillChange(notification: NSNotification) {
    if let userInfo = notification.userInfo,
        let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
        let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt {
        
        let frame = value.cgRectValue
        var intersection = frame.intersection(self.view.frame)
        
        if intersection.height == 0.0 {
            intersection = CGRect(x: intersection.origin.x, y: intersection.origin.y, width: intersection.width, height: 100)
        }
        
        UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(rawValue: curve), animations: { _ in
            self.bottomConstraint.constant = intersection.height
            self.view.layoutIfNeeded()
        })
        
    }
}

我是分割线

IOS输入框随键盘抬起防遮挡_第1张图片
图片都是瞎扯的,和主题没有关系

你可能感兴趣的:(IOS输入框随键盘抬起防遮挡)