Detecting a change to text in UITextfield

2019-03-23 08:44发布

问题:

I would like to be able to detect if some text is changed in a UITextField so that I can then enable a UIButton to save the changes.

回答1:

Take advantage of the UITextFieldTextDidChange notification or set a delegate on the text field and watch for textField:shouldChangeCharactersInRange:replacementString.

If you want to watch for changes with a notification, you'll need something like this in your code to register for the notification:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:theTextField];

Here theTextField is the instance of UITextField that you want to watch. The class of which self is an instance in the code above must then implement textFieldDidChange, like so:

- (void)textFieldDidChange:(NSNotification *)notification {
    // Do whatever you like to respond to text changes here.
}

If the text field is going to outlive the observer, then you must deregister for notifications in the observer's dealloc method. Actually it's a good idea to do this even if the text field does not outlive the observer.

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    // Other dealloc work
}


回答2:

Instead of observing notifications or implementing textField:shouldChangeCharacterInRange:replacementString:, it's easier to just add an event target:

[textField addTarget:self
              action:@selector(myTextFieldDidChange:)
    forControlEvents:UIControlEventEditingChanged];

- (void)myTextFieldDidChange:(id)sender {
    // Handle change.
}

Note that the event is UIControlEventEditingChanged and not UIControlEventValueChanged!

The advantages over the other two suggested solutions are:

  • You don't need to remember to unregister your controller with the NSNotificationCenter.
  • The event handler is called after the change has been made which means textField.text contains the text the user actually entered. The textField:shouldChangeCharacterInRange:replacementString: delegate method is called before the changes have been applied, so textField.text does not yet give you the text the user just entered – you'd have to apply the change yourself first.


回答3:

For that, first you need to have your textfield have it delegate reference assigned. And the delgate, should preferably be, the vew controller which is the files owner of the view. Which goes like

myTextField.delegate = myViewControllerReferenceVariable

And in your viewController interface, tell you will be implementing UITextFieldDelegate by

@interface MyViewController:UIViewController<UITextFieldDelegate>

And in your view controller implementation override

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

So the code will look like

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
     {
        text = [textfield.text stringByReplacingCharactersInRange:range withString:string];
        if (textfield == refToTextFieldYouWantToCheck) {
            if ( ! [textToCheck isEqualToString:text] ) {
               [theButtonRef setEnabled:YES];
            } 
         }
           return YES; //If you don't your textfield won't get any text in it
      }

You can also subscribe to notification which is sort of messy IMHO You can find how to do it here.



回答4:

Swift 3.0

Process 1

Create IBOutlet of UITextfiled and Add Target to text field.

 m_lblTxt.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControlEvents.editingChanged)

 func textFieldDidChange(textField:UITextField)
 {
     NSLog(textField.text!)
 }

Process 2

 m_lblTxt.delegate = self

 //MARK: - TextField Delegates
 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 
 {
      print(textField.text!)
      return true
 }


回答5:

You could create a variable to store the original string, then register with the notification center to receive UITextFieldTextDidChangeNotification event:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateButton:) name:UITextFieldTextDidChangeNotification object:nil];

Then, create a method to receive the notification, and compare the current value of the text field with the original value

-(void) updateButton:(NSNotification *)notification {
       self.myButton.enabled = ![self.myTextField.text isEqualToString:originalString];
}

Don't forget to de-register the notification when the view controller is deallocated.

[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];


回答6:

This can be accomplished in Interface Builder on the Editing Changed event of UITextField. Drag from it to your code and create an IBAction.

For example:

@IBAction func textFieldChanged(_ sender: UITextField) {
  print(sender.text)
}

This event is the same as described in other answers here in that the .text property contains the updated text input when it gets triggered. This can help clean up code clutter by not having to programmatically add the event to every UITextField in the view.



回答7:

You can add a class member like this NSString *changeTemp,then

changetemp = textfield;

if( change temp != textfild ){
    changetemp=textfild;
    NSLog(@" text is changed"
} else { 
    NSLog(@" text isn't changed"):
}