我如何通知 UITextField 中的更改? [英] How do i notify changes in UITextField?

查看:22
本文介绍了我如何通知 UITextField 中的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文本字段(一个用于用户名,另一个用于密码),我有一个按钮(用于登录).两个文本字段都将 clearButtonMode 设置为 YES(即我在文本字段的右端提供小十字 x 按钮,只需单击即可擦除该字段).

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....

提前致谢

推荐答案

您可以为两个字段使用 UITextFieldTextDidChangeNotification 通知,并相应地为您的按钮设置启用.

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

示例代码:

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

这篇关于我如何通知 UITextField 中的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆