swift之防止键盘遮挡输入框

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

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)
    }
}
FB6AA06E-FBDC-4253-B41A-DA679441CA8A.png
C45957C1-AE5D-4BB1-B0D6-B98B9F847345.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,416评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,246评论 4 61
  • 上周因为工作的调整,一下多出了几倍的事,加之请来的庆阳唢呐在录音、访谈和演出,“忙”简值成了忙忘了事。 古典老师说...
    黄虎阅读 337评论 0 12
  • 有时候,别人提出一个方案,你想改变他,变成你想要的结果。 但是经过争吵,争论之后,产生的结果往往还没有别人提出的第...
    新自由阅读 115评论 0 0
  • 写给有思考的女生,写给所有的男生,写给恋爱的人们。 下班前读了一篇公众号文章,有句话我很赞同,文章里说:没有经济基...
    Lin小懒阅读 2,302评论 0 2