【发布时间】:2013-07-03 11:58:35
【问题描述】:
我有两个UITextfield,两个cells,一个section,一个grouped UITableView,分别称为emailField和passwordField,他们将tag设置为0和1。我有一个@ 987654328@ 在navigationBar 的右边缘调用了loginButton。我希望在此视图进入屏幕时禁用该按钮,并希望在 textFields 都在其中输入文本时启用该按钮,否则该按钮被禁用。
这是创建按钮的代码。
_loginButton = [[UIBarButtonItem alloc] initWithTitle:@"Login"
style:UIBarButtonItemStyleDone
target:self
action:@selector(logging)];
_loginButton.enabled = NO;
self.navigationItem.rightBarButtonItem = _loginButton;
在UITextFieldtextFieldDidBegingEditing:方法中,我尝试实现这个功能。但它不起作用或工作不正确,这很奇怪。注意:textFields 添加为cell 的subview 而不是cell contentView's subview。
#pragma mark - UITextfield Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if (textField == self.emailField)
{
UITableViewCell *currentCell = (UITableViewCell *)textField.superview;
NSIndexPath *currentIndexPath = [self.tableView indexPathForCell:currentCell];
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:currentIndexPath.row+1 inSection:0];
UITableViewCell *nextCell = [self.tableView cellForRowAtIndexPath:nextIndexPath];
self.passwordField = (UITextField *)[nextCell viewWithTag:1];
if ([(UITextField *)[currentCell viewWithTag:0] text].length != 0 && [(UITextField *)[nextCell viewWithTag:1] text].length != 0)
{
self.loginButton.enabled = YES;
}
else
{
self.loginButton.enabled = NO;
}
}
}
我也尝试在按钮选择器方法中实现这个功能,但根本不起作用。
- (IBAction)logging
{
if (self.emailField.text.length > 0 && self.passwordField.text.length > 0)
{
self.loginButton.enabled = YES;
}
else
{
self.loginButton.enabled = NO;
}
}
这是怎么回事?
【问题讨论】:
-
你试过调试它吗?设置断点,看看你是否得到了正确的文本字段。
-
您的代码是否到达 self.loginButton.enabled = YES 语句?
-
使用 viewWithTag:0 时必须非常小心,因为 0 是视图标签的默认值。任何没有专门设置标签的视图都将返回 0。这可能不是您所期望的行为。
标签: ios cocoa-touch uitextfield uibarbuttonitem