Getting cursor position in a UITextView on the iPhone?

后端 未结 4 1420
一向
一向 2020-12-24 03:23

We have a UITextView in our iPhone app which is editable. We need to insert some text at the cursor location when the users presses some toolbar buttons but can\'t seem to

相关标签:
4条回答
  • 2020-12-24 03:50

    Like drewh said, you can use UITextView's selectedRange to return the insertion point. The length of this range is always zero. The example below shows how to it.

    NSString *contentsToAdd = @"some string";
    NSRange cursorPosition = [tf selectedRange];
    NSMutableString *tfContent = [[NSMutableString alloc] initWithString:[tf text]];
    [tfContent insertString:contentsToAdd atIndex:cursorPosition.location];
    [theTextField setText:tfContent];
    [tfContent release];
    
    0 讨论(0)
  • 2020-12-24 03:54

    Use UITextView selectedRange property to find the insertion point when the text view is first responder. Otherwise, when the view is not in focus, this property returns NSNotFound. If you need to know the cursor position in that case, consider subclassing UITextView and overriding canResignFirstResponder method, where you can store cursor position to a member variable.

    0 讨论(0)
  • 2020-12-24 03:59

    Have you tried UITextView.selectedRange? It returns an NSRange, whose location element should tell you, where the cursor is.

    0 讨论(0)
  • 2020-12-24 04:03

    Swift 4:

    // lets be safe, thus if-let
    if let cursorPosition = textView.selectedTextRange?.start {
        // cursorPosition is a UITextPosition object describing position in the text
    
        // if you want to know its position in textView in points:
        let caretPositionRect = textView.caretRect(for: cursorPosition)
    }
    

    We simply use textView.selectedTextRange to get selected text range and cursor position is at its start position.

    0 讨论(0)
提交回复
热议问题