如何在UITextView中获得NSRange的x,y位置

时间:2018-09-18 23:26:06

标签: ios swift

从Swift中的UITextView给出NSRange,我如何检索将其包裹的矩形的中心坐标? 我在这里能找到的所有答案都是针对Objective-c的。

1 个答案:

答案 0 :(得分:0)

根据Pushp's answer

let range: NSRange = (txtView.text as NSString).range(of: text)
let beginning: UITextPosition? = txtView.beginningOfDocument
let start: UITextPosition? = txtView.position(from: beginning!, offset: range.location)
let end: UITextPosition? = txtView.position(from: start!, offset: range.length)
let textRange: UITextRange? = txtView.textRange(from: start!, to: end!)
let rect: CGRect = txtView.firstRect(for: textRange!)