iOS: Programmatically move cursor up, down, left a

2020-03-26 03:31发布

问题:

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

 txtView.selectedRange = NSMakeRange(5, 0);

Now, if I have a cursor at an arbitrary position as shown in the image below, how can I move the cursor up, down, left and right?

回答1:

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.