简体   繁体   中英

How to know when UITextView became first responder

How to handle when uitextview became first responder. I have text in text view and I want when the view became active want to clear the text. How can I do that? Thanks in advance

You can definitely use a UITextViewDelegate method of:

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView

Just return YES and intercept inside that method. You can also do it for UITextFields with UITextFieldDelegate and:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

Hope that helps.

Previous answers do the job great for UITextBox, but if you have a custom class derived from NSResponder and need to know when it becomes first responder:

-(BOOL) becomeFirstResponder
{
    // Your stuff here
    return YES;
}

As above, you can override becomeFirstResponder but note that you must call the superclass implementation. If you don't, things like popping the keyboard on a text field won't work. ie

override func becomeFirstResponder() -> Bool {
  if super.becomeFirstResponder() {
    // set up the control state
    return true
  }

  return false
}

The Swift 4 solution

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {           
        return true
 }

textViewShouldBeginEditing actually triggers before the text view becomes the first responder.

textViewDidBeginEditing will trigger once the text view becomes the first responder and would be the best place to execute code that needs to know what the active textview is.

If you are not really worried about which field is active and just want to clear the text once the field is tapped on you could use either function.

EDIT: The same methods are available for text fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM