我使用以下代码将光标位置移动到距 UITextField
开头的 5 个字符处:
txtView.selectedRange = NSMakeRange(5, 0);
现在,如果我有一个光标在任意位置,如下图所示,我该如何上下左右移动光标?
最佳答案
左和右应该或多或少容易些。我想棘手的部分是顶部和底部。我会尝试以下方法。
您可以使用caretRect
方法找到光标的当前“帧”:
if let cursorPosition = answerTextView.selectedTextRange?.start {
let caretPositionRect = answerTextView.caretRect(for: cursorPosition)
}
然后向上或向下,我会使用该框架来计算 UITextView
坐标中的估计位置,使用 characterRange(at:)
(或者可能是 closestPosition(到 :)
),例如向上:
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
}
我以前没有真正做过,所以把这个当作一个应该适合你的大体方向。
所用方法的文档是 here .
关于iOS:以编程方式在 UITextView 中向上、向下、向左和向右移动光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49110807/