How do i notify changes in UITextField?

大城市里の小女人 提交于 2019-12-23 17:53:53

问题


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:@""];
}


来源:https://stackoverflow.com/questions/5715591/how-do-i-notify-changes-in-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!