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()
        })
        
    }
}

我是分割线

图片都是瞎扯的,和主题没有关系
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容