ios - 使用 `textField:shouldChangeCharactersInRange:

我正在使用下面的代码来尝试更新 textField2 的文本内容以匹配 textField1 的内容,只要用户键入 textField1

- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {    
  if (theTextField == textField1){    
     [textField2 setText:[textField1 text]];    
  }
}

但是,我观察到的输出是......

textField2 is "12", when textField1 is "123"

textField2 is "123", when textField1 is "1234"

...当我想要的是:

textField2 is "123", when textField1 is "123"

textField2 is "1234", when textField1 is "1234"

我做错了什么?

最佳答案

-shouldChangeCharactersInRange 被调用 before 文本字段实际更改其文本,这就是您获得旧文本值的原因。更新使用后获取文本:

[textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];

关于ios - 使用 `textField:shouldChangeCharactersInRange:` ,如何获取包含当前键入字符的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2198067/

相关文章:

ios - 在 iOS 应用程序中在哪里存储全局常量?

objective-c - Objective-C 中的 protected 方法

ios - 将 Project-Swift.h 导入到 Objective-C 类中...找不到文件

iphone - 以编程方式请求访问联系人

ios - 将 UIButton 字体大小调整为宽度

objective-c - 从 iOS 上的 UIView 将图像保存到应用程序文档文件夹

objective-c - #import 使用尖括号 < > 和引号 ""

ios - 如何使用 iOS 轻松调整/优化图像大小?

objective-c - 未找到体系结构 i386 的符号

objective-c - 警告 : "format not a string literal an