How to know when UITextView became first responder

99封情书 提交于 2020-01-01 23:10:56

问题


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


回答1:


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.




回答2:


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;
}



回答3:


The Swift 4 solution

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



回答4:


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. i.e.

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

  return false
}



回答5:


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.



来源:https://stackoverflow.com/questions/7022180/how-to-know-when-uitextview-became-first-responder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!