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

风格不统一 提交于 2019-12-01 08:01:19

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!