我正在使用下面的代码来尝试更新 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/