美文网首页swift 文章收集swift编程开发
swift之防止键盘遮挡输入框

swift之防止键盘遮挡输入框

作者: 就怕是个demo | 来源:发表于2016-01-06 14:29 被阅读1985次

    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

    相关文章

      网友评论

        本文标题:swift之防止键盘遮挡输入框

        本文链接:https://www.haomeiwen.com/subject/blvxkttx.html