Reputation: 93
I have a UITextView that says "This burger is ______" and I have an empty UITextField below it. I want it so that every character you type into the UITextField, the UITextView is updated immediately.
Right now, I have this implemented
- (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;
}
When I run the app and I want to type in tasty into the UITextField, this is what I get as the UITextView:
UITextView: "This burger is t ta tas tast tasty"
UITextField: "tasty"
It's replacing the "This burger is_____" string with the new version of the string that I'm making. I've set the UITextField as the delegate
Halp.
Upvotes: 1
Views: 94
Reputation: 6272
this is an easy mistake :)
The problem is that you are appending text to an already existing string:
NSString *stringWithTasty = [TextThisBurgerIs.text stringByAppendingString:newString];
When you press "t" you get "This burger is t".
Next when you press "a" you are appending "ta" to the string which is already contained in your text view (which is "This burger is t"). The result is therefore "This burger is t ta".
What you need to do is to store the original string "This burger is" and you should have:
NSString *stringWithTasty = [originalString stringByAppendingString:newString];
where originalString
is @"This burger is".
Or you can simply have:
NSString *stringWithTasty = [@"This burger is" stringByAppendingString:newString];
Upvotes: 2