iOS: Programmatically move cursor up, down, left and right in UITextView

后端 未结 1 2025
忘了有多久
忘了有多久 2021-01-14 04:56

I use the following code to move the cursor position to 5 characters from the beginning of a UITextField:

 txtView.selectedRange = NSMakeRange(5         


        
相关标签:
1条回答
  • 2021-01-14 05:31

    Left and right should be more or less easy. I guess the tricky part is top and bottom. I would try the following.

    You can use caretRect method to find the current "frame" of the cursor:

    if let cursorPosition = answerTextView.selectedTextRange?.start {
        let caretPositionRect = answerTextView.caretRect(for: cursorPosition)
    
    
    }
    

    Then to go up or down, I would use that frame to calculate estimated position in UITextView coordinates using characterRange(at:) (or maybe closestPosition(to:)), e.g. for up:

    let yMiddle = caretPositionRect.origin.y + (caretPositionRect.height / 2)
    let lineHeight = answerTextView.font?.lineHeight ?? caretPositionRect.height // default to caretPositionRect.height
    // x does not change
    let estimatedUpPoint = CGPoint(x: caretPositionRect.origin.x, y: yMiddle - lineHeight)
    if let newSelection = answerTextView.characterRange(at: estimatedUpPoint) {
        // we have a new Range, lets just make sure it is not a selection
        newSelection.end = newSelection.start
    
        // and set it
        answerTextView.selectedTextRange = newSelection
    } else {
        // I guess this happens if we go outside of the textView
    }
    

    I haven't really done it before, so take this just as a general direction that should work for you.

    Documentation to the methods used is here.

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