使用`textField:shouldChangeCharactersInRange:`,如何获取包含当前类型字符的文本? [英] Using `textField:shouldChangeCharactersInRange:`, how do I get the text including the current typed character?

查看:1278
本文介绍了使用`textField:shouldChangeCharactersInRange:`,如何获取包含当前类型字符的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的代码尝试让 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为12,当textField1为123时

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

textField2是123,当textField1是1234

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

...当我想要的是:

... when what I want is:


textField2为123,当textField1为123时

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

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:`,如何获取包含当前类型字符的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆