iOS:以编程方式在UITextView中上下左右移动光标 [英] iOS: Programmatically move cursor up, down, left and right in UITextView
问题描述
我使用以下代码将光标位置从UITextField
的开头移至5个字符:
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?
推荐答案
左右应该比较容易.我想最棘手的部分是顶部和底部.我会尝试以下方法.
Left and right should be more or less easy. I guess the tricky part is top and bottom. I would try the following.
您可以使用caretRect
方法找到光标的当前框架":
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)
}
然后向上或向下,我将使用该框架使用characterRange(at:)
(或者可能是closestPosition(to:)
)在UITextView
坐标中计算估计位置,例如向上:
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.
这篇关于iOS:以编程方式在UITextView中上下左右移动光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!