Swift监听键盘通知以及做出一些处理

作者: ZYiDa | 来源:发表于2018-01-19 09:30 被阅读495次

    之前也做过类似的功能,但是在Swift上面的效果不是很好。今天整理了一下之前小项目中的代码和思路,很好的解决了在登录界面登录按钮被键盘遮挡的问题。
    先看效果图

    xxoo

    如下

    注册键盘通知
    //MARK:监听键盘通知
        func registerNotification(){
            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(keyBoardWillShow(_ :)),
                                                   name: NSNotification.Name.UIKeyboardWillShow,
                                                   object: nil)
    
            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(keyBoardWillHide(_ :)),
                                                   name: NSNotification.Name.UIKeyboardWillHide,
                                                   object: nil)
        }
    
    根据键盘通知做出对应的操作
    
        //MARK:键盘通知相关操作
        @objc func keyBoardWillShow(_ notification:Notification){
    
            DispatchQueue.main.async {
    
                /*
                 每次键盘发生变化之前,先恢复原来的状态
                 y 是键盘布局的origin.y
                 y2 是登录按钮的origin.y+height
                 如果y>y2,登录按钮没有被遮挡,不需要向上移动;反之,按钮被遮挡,整体需要向上移动一部分
                 */
                self.view.center = CGPoint.init(x: Width/2, y: Height/2)
                let user_info = notification.userInfo
                let keyboardRect = (user_info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    
                let y = keyboardRect.origin.y
                let y2 = (self.nextStep?.frame.origin.y)! + (self.nextStep?.frame.size.height)! + 5
                let offset_y = y2 > y ? (y2-y):(0)
    
                UIView.animate(withDuration: 0.25, animations: {
                    self.view.center = CGPoint.init(x: Width/2, y: self.view.center.y - offset_y)
                })
            }
        }
    
        @objc func keyBoardWillHide(_ notification:Notification){
            DispatchQueue.main.async {
                self.view.center = CGPoint.init(x: Width/2, y: Height/2)
            }
        }
    
    
    释放键盘通知

    因为这里只有这两个通知,所以我选择了removeObserver(self)来移除所有通知,当然,你也可以根据通知名称来逐个移除。

    //MARK:释放键盘监听通知
        func releaseNotification(){
            NotificationCenter.default.removeObserver(self)
        }
    

    经测试,上面的方法在4.0-5.5英寸的iPhone设备上正常运行。

    不足的地方还请多多指教,谢谢各位了。

    相关文章

      网友评论

        本文标题:Swift监听键盘通知以及做出一些处理

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