问题描述
我正在使用下面的代码尝试让 textField2
的文本内容更新以匹配 textField1
只要用户键入 textField1
。
I'm using the code below to try and have textField2
's text content get updated to match textField1
's whenever the user types in textField1
.
- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {
if (theTextField == textField1){
[textField2 setText:[textField1 text]];
}
}
然而,我观察到的输出是......
However, the output I observe is that...
textField2是123,当textField1是1234
textField2 is "123", when textField1 is "1234"
...当我想要的是:
... when what I want is:
textField2为1234,当textField1是1234
textField2 is "1234", when textField1 is "1234"
我做错了什么?
推荐答案
-shouldChangeCharactersInRange
在文本字段实际更改其文本之前调用,这就是您获取旧文本值的原因。要在更新后使用文本:
-shouldChangeCharactersInRange
gets called before text field actually changes its text, that's why you're getting old text value. To get the text after update use:
[textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];
这篇关于使用`textField:shouldChangeCharactersInRange:`,如何获取包含当前类型字符的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!