UITextView insert text in the textview text

后端 未结 6 1006
谎友^
谎友^ 2020-12-10 03:16

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 ne

相关标签:
6条回答
  • 2020-12-10 03:22

    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"];
    
    0 讨论(0)
  • 2020-12-10 03:23
    - (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
    }
    
    0 讨论(0)
  • 2020-12-10 03:33

    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];
    }
    
    0 讨论(0)
  • 2020-12-10 03:38

    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.  
    
    }
    
    0 讨论(0)
  • 2020-12-10 03:39

    UITextview has an insertText method and it respects cursor position.

    - (void)insertText:(NSString *)text
    

    for example:

    [myTextView insertText:@"\n\n"];
    
    0 讨论(0)
  • 2020-12-10 03:40

    For Swift 3.0

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

    Example:

    textView.insertText("yourText")
    
    0 讨论(0)
提交回复
热议问题