uibutton - 如何通知 UITextField 中的更改?

标签 uibutton uitextfield

我有两个文本字段(一个用于用户名,另一个用于密码),我有一个按钮(用于登录)。两个文本字段都将 clearButtonMode 设为 YES(也就是说,我在文本字段的右端提供了一个小十字 x 按钮,以便一键删除该字段)。

最初,登录按钮被禁用。当且仅当两个文本字段都应至少包含一个字母时,我才想启用它。单击十字按钮时它也应该起作用。

请建议我如何做到这一点......

提前致谢

最佳答案

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

示例代码:

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

关于uibutton - 如何通知 UITextField 中的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5715591/

相关文章:

ios - 如何为 UIButton 创建动态叠加层?

ios - 无法在没有错误的情况下在自定义 UITableView 上添加 UIButton

ios - 如何以编程方式将 UIView(或更具体地说,UITextAreas)嵌入到文本中?

ios - 检查 UITextField 中的更改

iphone - 自定义表格单元格的 uitextfield

ios - 如何在多个 View 中重用相同的 UIButton

swift - swift 中的编程按钮不起作用

swift - 强制 UIButton 只有一个标题行

ios - UITextField 失去焦点事件

swift - 在 UITableView 中为不同的 UITextField 设置 inputView