how to insert text at any cursor position in uitextview?

前端 未结 4 956
走了就别回头了
走了就别回头了 2021-02-13 01:42

i want to implement Code by which i can start to insert text at any position of cursor in UITextView in iphone sdk

any idea? thank you in advance..

i refereed th

相关标签:
4条回答
  • 2021-02-13 02:09

    The simplest way (but it won't replace selected text) is to use the insertText: method:

    [textView insertText:@"some text you want to insert"];
    

    UITextView conforms to UITextInput which itself conforms to UIKeyInput.

    0 讨论(0)
  • 2021-02-13 02:12

    Dan's answer is manually changing the text. It's not playing well with UITextView's UndoManager.

    Actually it's very easy to insert text with UITextInput protocol API, which is supported by UITextView and UITextField.

    [textView replaceRange:textView.selectedTextRange withText:insertingString];
    

    Note: It's selectedTextRange in UITextInput protocol, rather than selectedRange

    0 讨论(0)
  • 2021-02-13 02:14

    This is what I use with a custom keyboard, seems to work ok, there may be a cleaner approach, not sure.

    NSRange range = myTextView.selectedRange;  
    NSString * firstHalfString = [myTextView.text substringToIndex:range.location];  
    NSString * secondHalfString = [myTextView.text substringFromIndex: range.location];  
    myTextView.scrollEnabled = NO;  // turn off scrolling  
    
    NSString * insertingString = [NSString stringWithFormat:@"your string value here"];
    
    myTextView.text = [NSString stringWithFormat: @"%@%@%@",  
                     firstHalfString,  
                     insertingString,  
                     secondHalfString];  
    range.location += [insertingString length];  
    myTextView.selectedRange = range;  
    myTextView.scrollEnabled = YES;  // turn scrolling back on.
    
    0 讨论(0)
  • 2021-02-13 02:20

    Here is the Glorfindel's answer in Swift3. The text its inserting here it pulls out of the clipboard.

    if let textRange = myTextView.selectedTextRange {
       myTextView.replace(textRange, withText:UIPasteboard.general.string!)
    }
    
    0 讨论(0)
提交回复
热议问题