如何获得当前插入符号的CGRect

时间:2017-04-26 12:21:22

标签: ios swift

我想在UITextView中以CGRect获取当前插入符号的位置,但似乎没有任何信息。即使the official documentation,我也无法想象如何利用这种方法并找到解释。现在我可以知道在UITextView而不是CGRect中获得偏移的方法。但是,我真的想知道CGRect

任何评论都应该受到高度赞赏。 谢谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

extension UITextView {
    var caret: CGRect? {
        guard let selectedTextRange = self.selectedTextRange else { return nil }
        return self.caretRect(for: selectedTextRange.end)
    }
}

并像这样使用它:

let textView: UITextView = ...
if let caret = textView.caret {
    // Do your thing here.
} else {
    // Caret is undefined. 
}

顺便说一下,你走在正确的轨道上:-)上述解决方案基于你刚刚提到的UITextInput方法:

func caretRect(for position: UITextPosition) -> CGRect
  

返回一个用于在给定插入点绘制插入符号的矩形。

UITextPosition参数表示文本容器中的位置;换句话说,它是文本显示视图中支持字符串的索引。

答案 1 :(得分:-2)

//rect is an object of CGRect
var rect = TextView.frame