UITextView insert text in the textview text

2020-02-05 06:43发布

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

6条回答
唯我独甜
2楼-- · 2020-02-05 07:09

This is a correct answer!

The cursor position is also right.

A scroll position is also right.

- (void) insertString: (NSString *) insertingString intoTextView: (UITextView *) textView
{
    [textView replaceRange:textView.selectedTextRange withText:insertingString];
}
查看更多
Juvenile、少年°
3楼-- · 2020-02-05 07:20

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"];
查看更多
看我几分像从前
4楼-- · 2020-02-05 07:22

For Swift 3.0

You can append text by calling method insertText of UITextView Instance.

Example:

textView.insertText("yourText")
查看更多
虎瘦雄心在
5楼-- · 2020-02-05 07:23

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.  

}
查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-02-05 07:24

UITextview has an insertText method and it respects cursor position.

- (void)insertText:(NSString *)text

for example:

[myTextView insertText:@"\n\n"];
查看更多
我命由我不由天
7楼-- · 2020-02-05 07:25
- (void)insertStringAtCaret:(NSString*)string {
    UITextView *textView = self.contentCell.textView;

    NSRange selectedRange = textView.selectedRange;
    UITextRange *textRange = [textView textRangeFromPosition:textView.selectedTextRange.start toPosition:textView.selectedTextRange.start];

    [textView replaceRange:textRange withText:string];
    [textView setSelectedRange:NSMakeRange(selectedRange.location + 1, 0)];

    self.changesDetected = YES; // i analyze the undo manager in here to enabled/disable my undo/redo buttons
}
查看更多
登录 后发表回答