立即从UITextField更新UITextView字符串

时间:2015-08-20 20:44:58

标签: ios objective-c uitextfield uitextview

我有一个UITextView说"这个汉堡是______"我下面有一个空的UITextField。我希望它能让您在UITextField中输入的每个字符都立即更新UITextView。

现在,我实施了这个

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *stringWithTasty = [TextThisBurgerIs.text stringByAppendingString:newString];

[TextThisBurgerIs setText:stringWithTasty];

return YES;
}

当我运行应用程序并且我想输入UITextField中的nice时,这就是我得到的UITextView:

UITextView: "This burger is t ta tas tast tasty"
UITextField: "tasty"

它取代了"这个汉堡是_____"字符串与我正在制作的新版本的字符串。我已将UITextField设置为委托

HALP。

1 个答案:

答案 0 :(得分:2)

这是一个容易犯的错误:)

问题是您要将文本附加到现有字符串:

NSString *stringWithTasty = [TextThisBurgerIs.text stringByAppendingString:newString];

当你按“t”时,你会得到“这个汉堡就是”。

接下来当您按“a”时,您将“ta”附加到文本视图中已包含的字符串(即“此汉字为t”)。因此结果是“这个汉堡就是这个”。

您需要做的是存储原始字符串“This burger is”,您应该:

NSString *stringWithTasty = [originalString stringByAppendingString:newString];

其中originalString是@“这个汉堡是”。

或者你可以简单地拥有:

NSString *stringWithTasty = [@"This burger is" stringByAppendingString:newString];