iOS:以编程方式在 UITextView 中向上、向下、向左和向右移动光标

标签 ios objective-c position cursor uitextview

我使用以下代码将光标位置移动到距 UITextField 开头的 5 个字符处:

 txtView.selectedRange = NSMakeRange(5, 0);

现在,如果我有一个光标在任意位置,如下图所示,我该如何上下左右移动光标?

enter image description here

最佳答案

左和右应该或多或少容易些。我想棘手的部分是顶部和底部。我会尝试以下方法。

您可以使用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/

相关文章:

objective-c - UITableView:viewForHeaderInSection - 标题文本?

ios - 如何将特定委托(delegate)传递给 UIApplicationMain

ios - initWithCoder : function is not called from unarchiveObjectWithData:

jquery-ui - jQuery UI 对话框定位: adjust position top by 20px -

ios - 不清楚 "Type of expression is ambiguous without more context"错误

objective-c - 操作完成后如何隐藏或删除 UIwebview?

ios - 在 swift 3 中使用 NotificationCenter 停止 Dispatchqueue

css - 将元素定位在动态调整大小的元素中间

html - CSS - 字间距在进行绝对定位时不起作用

ios - 如何检测应用程序在 iOS 中首次启动?