【问题标题】:iOS: Programmatically move cursor up, down, left and right in UITextViewiOS:以编程方式在 UITextView 中上下左右移动光标
【发布时间】:2018-03-05 12:44:11
【问题描述】:

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

 txtView.selectedRange = NSMakeRange(5, 0);

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

【问题讨论】:

  • 左右,这很简单,只是不是NSMakeRange(something, 0);+1 或-1(注意边界)。对于向上/向下,这更棘手,因为您必须知道线,根据该线中的位置的当前范围。也许有一些可能的线索:stackoverflow.com/questions/17557845/…
  • @NiravKotecha 不,这里的问题不同。
  • @Larme 好的,我会自己实现它。我希望找到一个更优雅的解决方案。
  • 添加您当前的场景(详细流程),以便其他人能够很好地理解并且他们会帮助您:)

标签: ios objective-c position cursor uitextview


【解决方案1】:

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

您可以使用caretRect方法找到光标当前的“帧”:

if let cursorPosition = answerTextView.selectedTextRange?.start {
    let caretPositionRect = answerTextView.caretRect(for: cursorPosition)


}

然后向上或向下,我将使用该框架来计算 UITextView 坐标中的估计位置,使用 characterRange(at:)(或者可能是 closestPosition(to:)),例如向上:

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

【讨论】:

    猜你喜欢
    • 2011-03-10
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多