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

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注册键盘通知)