Detect Start and Stop Editing UITextView

后端 未结 4 1724
名媛妹妹
名媛妹妹 2021-02-06 22:39

How can I call some code upon entering a UITextView (user taps to edit it) and leaving the view (user taps to leave it)?

Appreciate any help.

4条回答
  •  一向
    一向 (楼主)
    2021-02-06 23:32

    You could also implement the UITextViewDidChange delegate methods. I use the code below in my app for taking quick notes. Whenever the user has entered a character, the observer catches this from the notification center and calls the saveText method.

    Here's how:

    Add this line to the viewDidLoad method:

    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];
    

    and these lines at the appropriate place in your code (like in the section that handles the text view delegate methods. TIP: Use pragma marks for this (#pragma mark - TextView Delegate Methods):

    - (void)textViewDidChange:(UITextView *)textView{
    
        NSLog(@"textViewShouldEndEditing"); // Detect in log output if the method gets called
        [self saveText:nil]; // Call any method you like
    
    }
    

提交回复
热议问题