How do i notify changes in UITextField?

2019-07-04 04:20发布

问题:

I have two text fields (one for username & another is for password) and i have one button (for login). Both text fields have clearButtonMode as YES (that is i am providing the small cross x button in the right end of the text field to erase the field with an one click).

Initially, the login button is disabled. I want to enable it if & only if both text fields should have atleast one letter. Also it should work while clicking on the cross button.

Please suggest me how to do this....

Thanks in Advance

回答1:

You can make use of the UITextFieldTextDidChangeNotification notification for both fields and set enabled for your button accordingly.

Example code:

// add the observer
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(textFieldDidChange:) 
                                             name:@"UITextFieldTextDidChangeNotification" 
                                          object:nil];

// the method to call on a change
- (void)textFieldDidChange:(NSNotification*)aNotification 
{
    myButton.enabled = [self bothTextFieldsHaveContent];
}

- (BOOL)bothTextFieldsHaveContent
{   
    return ![self isStringEmptyWithString:textField1.text) && 
           ![self isStringEmptyWithString:textField2.text);
}

// a category would be more elegant
- (BOOL)isStringEmptyWithString:(NSString *)aString
{
    NSString * temp = [aString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return [temp isEqual:@""];
}