The method of Swift3 listening to the change of UITextView text in iOS development three methods of of

  • 2021-07-03 00:55:50
  • OfStack

In addition to UITextField, UITextView is often used in the project, so it is inevitable that there will be a need to monitor the amount of text in the UITextView text box. Here are two common ways in swift3

Mode 1: Global notification

1. Notice of Registration

Register in place to listen for global notifications of UITextView text changes


//UITextView  Two methods of listening for starting input 
// Method 1: Notice 
NotificationCenter.default.addObserver(self, selector: #selector(ComposeVC.textViewChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)

2. Implement the listening method here named textViewChange


@objc fileprivate func textViewChange() {
XWLog("textView Text change  :\(composeTextView.text)")
}

3. Don't forget the ecstasy notification in the controller


// Remove notification 
deinit {
NotificationCenter.default.removeObserver(self)
}

Mode 2: Proxy

1. Set up the proxy


//1. Set up proxy 
composeTextView.delegate = self

2. Follow the proxy protocol and implement the proxy method


//MARK: - TEXTVIEW DELEGATE
extension ComposeVC : UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
if textView.text.lengthOfBytes(using: .utf8) > 0 {
// Text box with more than one text 0  Perform corresponding operations 
}else{
// The number of words in the text box is equal to 0  Perform corresponding operations 
}
}
}

Related articles: