ios - 多次调用 textFieldShouldEndEditing

标签 ios iphone objective-c uitextfield uitextfielddelegate

我正在处理具有多个 UITextField 对象的 View 。我的 View Controller 用作 UITextFieldDelegate,我已经实现了 (BOOL)textFieldShouldEndEditing:(UITextField *)textField 方法来保存和验证正在显示的记录。

如果用户在编辑项目后单击“完成”按钮并且保存/验证失败,则会显示 UIAlertView 并且用户会停留在 UITextField 验证失败。

我的问题是——当用户点击 UITextField 时,将无法保存/验证到另一个 UITextField,然后 (BOOL )textFieldShouldEndEditing:(UITextField *)textField方法被多次调用,多次弹出UIAlertView

为什么 (BOOL)textFieldShouldEndEditing:(UITextField *)textField 在用户单击键盘上的“完成”时调用一次,但在用户单击另一个 UITextField< 时调用多次?

这是我的代码:

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    NSLog(@"textFieldShouldEndEditing called by textField with text=%@", textField.text);

    currentItem.nameOrNumber = nameOrNumber.text;

    // Try to save the managed object.
    NSError *error = nil;
    if (![[currentItem managedObjectContext] save:&error]) {        
        UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Uh Oh!",@"")
                                                             message:[error localizedDescription]
                                                            delegate:self
                                                   cancelButtonTitle:NSLocalizedString(@"OK",@"")
                                                   otherButtonTitles:nil];
        [errorAlert show];
        [errorAlert release];
        shouldEnd = NO;
    }

    return shouldEnd;
}

最佳答案

我认为您的问题出在编辑文本字段并直接点击另一个文本字段时调用文本字段方法的顺序。

如果我没记错的话,应该是这样的(你在A上编辑然后点击B)

  • textFieldShouldBeginEditing 字段 B
  • textFieldShouldEndEditing 字段 A
  • textFieldDidEndEditing 字段 A
  • textFieldDidBeginEditing 字段 B

所以当你在 textFieldShouldEndEditing 方法中时,文本字段 B 已经成为第一响应者。因此,当您使 UIAlertView 出现时,B 会失去焦点,因此也会调用 textFieldShouldEndEditing!

当我想在 textField 开始编辑时提升 View 时,这对我来说也是个问题。我找到的解决方案是创建一个 bool 类变量,指示我当前是否正在从一个文本字段切换到另一个文本字段。 我在 textFieldShouldBeginEditing 中将其设置为 TRUE,在 textFieldDidBeginEditing 中将其设置为 FALSE。当您在 textFieldShouldEndEditing 中时,如果它设置为 TRUE,则意味着用户直接点击了另一个文本字段。然后你只需要找到正确的方法来只进行一次测试(也许 shouldEndEditing 应该返回 false 或其他东西)。

关于ios - 多次调用 textFieldShouldEndEditing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3121440/

相关文章:

objective-c - 如何在 iOS 10 中安排本地通知( objective-c )

ios - 在 Swift 中将数据从 View Controller 传递到 Child Controller

ios - 在非游戏应用程序中使用 Sprite 来提高静态视网膜图形的可管理性是否明智?

ios - Spritekit 在场景中添加节点但不移动?

iphone - 内容定位到 UIScrollView 中

ios - Uicollectionview 单元格宽度问题 iOS 10

iphone - 动态检查类是否通过 respondsToSelector : 响应选择器

ios - NSString floatValue,不适用于大数字

objective-c - 如何以编程方式将字体复制到/System/Library/Fonts/?

iphone - 用于选择器 View iPhone 的 JSON 数组