How to make a UITextView call the addTarget method

for swift version 3+

  1. add UITextViewDelegate to your class
  2. add delegate to your textview like this :
    self.mytextview.delegate = self
  3. add this method :

    func textViewDidChange(_ textView: UITextView){ 
        print("entered text:\(textView.text)")    
    }
    

Based on the information in the comments, what you'd like to do is update a local variable when the user types in a UITextView.

So try something like this (I assume you have a UIViewController subclass, and it's view has the UITextView in questions as a subview):

In your view controller, create an IBOutlet to your UITextView if using IB, or just a regular reference if not. Then another property for the NSString variable you want to store the text into.

NOTE: Make sure this view controller conforms to the UITextViewDelegate protocol as shown below.

@interface BBViewController () <UITextViewDelegate> //Note the protocol here

@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (strong, nonatomic) NSString *userInput;

@end

Then, hook up the text view's delegate: (Or do this in IB)

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.textView.delegate = self;
}

Then when the user interacts with the text in that text view, it will send the proper delegate methods and you can update your variable appropriately.

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView {

    self.userInput = textView.text;
    NSLog(@"userInput %@", self.userInput); //Just an example to show the variable updating
}

You can achieve what you want using notifications.

//Listen to notifications :

NotificationCenter.default.addObserver(textView,
            selector: #selector(textDidChange),
            name: NSNotification.Name.UITextViewTextDidChange,
            object: nil)

//the function called when changed

    @objc private func textDidChange() {
        ...
    }

//make sure to release to observer as well
            NotificationCenter.default.removeObserver(textView,
            name: NSNotification.Name.UITextViewTextDidChange,
            object: nil)

Tags:

Ios

Uitextview