我正在尝试使用舍入的rect突出显示textView中的几个单词。一切似乎都很好,除了换行符让我出乎意料之外。
override func draw(_ rect: CGRect) {
super.draw(rect)
for range in backgroundRangeArray {
self.layoutManager.enumerateEnclosingRects(forGlyphRange: range, withinSelectedGlyphRange: range, in: textContainer) { (rect, _) in
var newRect = rect
newRect.origin.y += self.spacing
newRect.size.height -= self.spacing + 3
let bezierPath = UIBezierPath(roundedRect: newRect, cornerRadius: 2)
self.highlightedTextColor.setFill()
bezierPath.fill()
bezierPath.close()
}
}
}
答案 0 :(得分:2)
如果我做对了,您就有希望在同一行上的字符串范围。如果是这样,您可以使用no-break space
替换这些范围内的常规空格
for range in backgroundRangeArray {
text = text?.replacingOccurrences(of: " ", with: "\u{00a0}", options: .caseInsensitive, range: range)
}