iOS 在UITextView中查找某个Range所在的Rect

 

 

代码如下(Swift 4):

 

extension UITextView {
    
    /// 查找文本范围所在的矩形范围
    ///
    /// - Parameter range: 文本范围
    /// - Returns: 文本范围所在的矩形范围
    func rect(forStringRange range: NSRange) -> CGRect? {
        
        guard let start = self.position(from: self.beginningOfDocument, offset: range.location) else { return nil }
        guard let end = self.position(from: start, offset: range.length) else { return nil }
        guard let textRange = self.textRange(from: start, to: end) else { return nil }
        let rect = self.firstRect(for: textRange)
        return self.convert(rect, from: self.textInputView)
    }
    
}

 

posted @ 2018-11-27 21:13  Ficow  阅读(858)  评论(0编辑  收藏  举报