1

i have a UITextView in which i have to write programmatically multiple lines. When i do this :

        [textView setText:@"String number 1\n"];
        [textView setText:@"String number 2\n"];

i get only : String number 2 as if it's writing the line over the other. I appreciate any suggestions :)

Malloc
  • 15,434
  • 34
  • 105
  • 192

4 Answers4

2

As the name suggests, setText: is a setter: it replaces the existing text.

That's quite like if you had an int val and you were doing:

val = 5;
val = 8;

Of course at the end val will be equal to 8 and the value 5 will be lost. Same thing here.


Instead, you need to create a string that contains all the lines, and affect directly to the textView:

[textView setText:@"Line1\nLine2\nLine3\n"];

If you need to do it incrementally, say you need to add text to existing text in the textView, first retrieve the existing text, append the new line, and set the new text back:

// get the existing text in the textView, e.g. "Line1\n", that you had set before
NSString* currentText = [textView text];
// append the new text to it
NSString* newText = [currentText stringByAppendingString:@"New Line\n"];
// affect the new text (combining the existing text + the added line) back to the textView
[textView setText:newText];
AliSoftware
  • 32,623
  • 6
  • 82
  • 77
1

setText replace whole content of textView. You better to prepare result string and than set it by single setText method call. for example:

NSString *resultString = [NSString stringWithFormat:@"%@%@", @"String 1\n", @"String 2\n"];
[textView setText:resultString];
user478681
  • 8,330
  • 4
  • 26
  • 34
1

you can append the strings :

mTextview.text = [mTextview.text stringByAppendingString:aStr];
Maulik
  • 19,348
  • 14
  • 82
  • 137
-1

According to How to create a multiline UITextfield?, UITextField is single-line only. Instead, use a UITextView.

In addition, as others have pointed out, if you call setText a second time, you'll overwrite the previous value. Instead, you should do something like this:

[textView setText:@"String number 1\nString number 2"]
Community
  • 1
  • 1
Edward Dale
  • 29,597
  • 13
  • 90
  • 129