How would I go about adding text to a UITextView without replacing the previous text?
So far I have a UITextView and a UIButton that adds the text to the UITextView, but I would like the text field to append more text every time you hit the button instead of completely deleting the text and replacing it.
Here are some ways to overcome obstacles in iOS development:
Look at the documentation for the particular class you’re trying to manipulate. In this case,
UITextViewdocumentation can be found within Xcode or online.Command-Click on
UITextViewor any other object anywhere in your code, and it will bring you to the header file for that class. The header file will list every public method and property.Look at your existing code. I’m assuming that since you have a button that adds text to a
UITextView, you understand how to set its text. 99% of the time you’ll find that any setter (mutator) methods will have a corresponding getter (accessor) method. In this case,UITextViewhas a method calledsetText:and a matching method just calledtext.Finally,
NSStringhas a convenience method calledstringWithFormat:that you can use to concatenate (join) two strings, among other very useful things.%@is the format specifier for a string. For example, to combine two strings,stringOneandstringTwo, you could do the following:NSString *string = [NSString stringWithFormat:@"%@ %@", stringOne, stringTwo];I will leave you to come up with the answer as to how to combine
NSStringstringWithFormat:andUITextFieldtextandsetText:to achieve what you’d like to accomplish.Edit:
The OP was unable to figure out how to utilize the information above so a complete code sample has been provided below.
Assume you have synthesized property (possibly an
IBOutlet)UITextViewthat you have initialized calledmyTextView. Assume also that we are currently in the method scope of the method that gets called (yourIBAction, if you’re using IB) when you tap yourUIButton.Explanation:
myTextView.textgrabs the existing text inside of theUITextViewand then you simply append whatever string you want to it. So if the text view is originally populated with the text “Hello world” and you clicked the button three times, you would end up with the following progression:Initial String: @”Hello world”
Tap one: @”Hello world this is some new text”
Tap Two: @”Hello world this is some new text this is some new text”
Tap Three: @”Hello world this is some new text this is some new text text this is some new text”