Detecting a change to text in UITextfield

前端 未结 7 2003
轮回少年
轮回少年 2021-02-07 02:15

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.

7条回答
  •  野性不改
    2021-02-07 02:34

    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
    }
    

提交回复
热议问题