nfoggia nfoggia - 4 months ago 17
iOS Question

NSString UITextView without replacing previous text

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.

Answer

Here are some ways to overcome obstacles in iOS development:

  1. Look at the documentation for the particular class you're trying to manipulate. In this case, UITextView documentation can be found within Xcode or online.

  2. Command-Click on UITextView or 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.

  3. 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, UITextView has a method called setText: and a matching method just called text.

Finally, NSString has a convenience method called stringWithFormat: 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, stringOne and stringTwo, 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 NSString stringWithFormat: and UITextField text and setText: 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) UITextView that you have initialized called myTextView. Assume also that we are currently in the method scope of the method that gets called (your IBAction, if you're using IB) when you tap your UIButton.

[myTextView setText:[NSString stringWithFormat:@"%@ %@", myTextView.text, @"this is some new text"]];

Explanation: myTextView.text grabs the existing text inside of the UITextView and 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"