iOS 开发之路(登陆页键盘遮挡输入框问题)一

2019-09-19 15:46:09 浏览数 (1)

      在学习开发登陆页的时候,遇到的问题分享如下:

    首先是swift 3.0 中,NotificationCenter 设置 selector 如下:

代码语言:javascript复制
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!    //注意这里要在storyboard对最底部的控件设置约束,然后连线到.swift文件进行绑定
  override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillChange(notification:)),  
             name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    点击空白处取消弹出的键盘

代码语言:javascript复制
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    键盘改变事件,防止键盘遮住输入框

代码语言:javascript复制
    // 键盘改变
    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)
            //当键盘消失,让view回归原始位置
            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.0,
                                       options: UIViewAnimationOptions(rawValue: curve), animations: {
                                        _ in
                                        //改变下约束
                                        self.bottomConstraint.constant = intersection.height
                                        self.view.layoutIfNeeded()
            }, completion: nil)
        }
    }

    后续肯定还会遇到很多问题,我会尽量把我遇到的问题以及解决办法记录下来供后来者学习。

    顺便吐槽一下,从安卓转过来,发现好多问题给出的解决方案都是 Object-C ,而且 Swift 版本更迭,变化很大,网上很多的解决方案经常需要自己微小调动才能正常使用。给我这样的新手带来好多麻烦。

    注:开发环境是Xcode 8.1 测试平台是 iOS 10.0

0 人点赞