美文网首页
ios10版本textView和textField注册键盘通知

ios10版本textView和textField注册键盘通知

作者: yytester | 来源:发表于2018-11-14 16:16 被阅读25次

    ios10版本textView和textField注册键盘通知

        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            print("Textfield获得焦点,点击Return键")
            textField.resignFirstResponder()
            return true
        }
        
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            
            if(text == "\n") {
                print("textview获得焦点,点击return键")
                textView.resignFirstResponder()
                return false
            }
            return true
        }
        
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            
            //注册键盘出现通知
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
            
            //注册键盘隐藏通知
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(_:)), name: UIResponder.keyboardDidHideNotification, object: nil)
        }
        
        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillAppear(animated)
       
            //注销键盘出现通知
            NotificationCenter.default.removeObserver(self,name:UIResponder.keyboardDidShowNotification,object:nil)
            
            //注销键盘隐藏通知
            NotificationCenter.default.removeObserver(self,name:UIResponder.keyboardDidHideNotification,object:nil)
    
        }
        
        
        @objc func keyboardDidShow(_ notification: Notification){
            print("键盘打开")
        }
        
        @objc func keyboardDidHide(_ notification: Notification){
            print("键盘关闭")
        }
        
    

    相关文章

      网友评论

          本文标题:ios10版本textView和textField注册键盘通知

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