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


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

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

      @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)

        } 

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

        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            self.view.endEditing(true)
        }

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

        // 键盘改变
        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,  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 

  • 相关阅读:
    DAS存储未死,再次欲获重生
    Minimum edit distance(levenshtein distance)(最小编辑距离)初探
    AC自己主动机
    手动脱UPX 壳实战
    edge中断分析
    ubuntu默认的Python版本号修改
    Linux 下 pushd,popd,cd- 用法
    目标检测算法的历史及分类
    openjtag 的硬件连接踩坑历程
    ubuntu 16.04 python版本切换(python2和python3)
  • 原文地址:https://www.cnblogs.com/jiajin/p/6020713.html
Copyright © 2020-2023  润新知