使用NSLayoutManager的这个API,传入字符在整个文本的NSRange,和当前TextView的textContainer。
open func boundingRect(forGlyphRange glyphRange: NSRange, in container: NSTextContainer) -> NSRect
简单示例
let str = "123321123"
let ranges = getPatternRangeArr(pattern: "123", content: str)
for i in 0..<ranges.count {
let r = ranges[i]
let rect = textView.layoutManager.boundingRect(forGlyphRange: r, in: textView.textContainer)
}
获取字符NSRange的方法
func getPatternRangeArr(pattern: String,content: String) -> [NSRange] {
var ranges:[NSRange] = []
do {
let regular = try NSRegularExpression(pattern: pattern,options: .caseInsensitive)
let results = regular.matches(in: content,options: .reportProgress, range: NSRange(location: 0, length: content.count))
for r in results {
ranges.append(r.range)
}
} catch {
print(error)
}
return ranges
}
网友评论