立即从 UITextField 更新 UITextView 字符串

Update UITextView string from UITextField immediately

我有一个显示 "This burger is ______" 的 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 中输入 tasty 时,这就是我作为 UITextView 得到的内容:

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

它将 "This burger is_____" 字符串替换为我正在制作的新版本字符串。我已将 UITextField 设置为委托

哈尔普。

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

问题是您将文本附加到已经存在的字符串中:

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

当您按 "t" 时,您会得到 "This burger is t"。

接下来,当您按 "a" 时,您会将 "ta" 附加到已包含在文本视图中的字符串(即 "This burger is t")。因此结果是 "This burger is t ta".

你需要做的是存储原始字符串"This burger is",你应该有:

NSString *stringWithTasty = [originalString stringByAppendingString:newString];

其中 originalString 是 @"This burger is".

或者您可以简单地拥有:

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