views:

423

answers:

2

I want to have to occasionally insert text into the UITextView text object. For example, if the user presses the "New Paragraph" button I would like to insert a double newline instead of just the standard single newline.

How can I go about such? Do i have to read the string from UITextView, mutate it, and write it back? Then how would I know where the pointer was?

Thanks

+1  A: 

Since the text property of UITextView is immutable, you have to create a new string and set the text property to it. NSString has an instance method (-stringByAppendingString:) for creating a new string by appending the argument to the receiver:

textView.text = [textView.text stringByAppendingString:@"\n\n"];
Martin Gordon
need to deal with fact that this might not be at end of the string. Some insertStringAtPoint-like function? What?
John Smith
Found it! it actually is insertString:atIndex:
John Smith
You might want to set textView.scrollEnabled = NO before updating textView.text; this prevents annoying scrolling to the end of text view
Ziga Kranjec
A: 

Here's how I implemented it and it seems to work nicely.

- (void) insertString: (NSString *) insertingString intoTextView: (UITextView *) textView  
{  
    NSRange range = textView.selectedRange;  
    NSString * firstHalfString = [textView.text substringToIndex:range.location];  
    NSString * secondHalfString = [textView.text substringFromIndex: range.location];  
    textView.scrollEnabled = NO;  // turn off scrolling or you'll get dizzy ... I promise  

    textView.text = [NSString stringWithFormat: @"%@%@%@",  
      firstHalfString,  
      insertingString,  
      secondHalfString];  
    range.location += [insertingString length];  
    textView.selectedRange = range;  
    textView.scrollEnabled = YES;  // turn scrolling back on.  

}
Brian Moncur