UITextView 正确高亮单词

UITextView correctly highlight words

我试图用圆角矩形突出显示 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()
        }
    }
}

(注意 特殊字符 之间不需要的 space)

如果我没记错的话,你有一系列的字符串要放在同一行上。如果是这样,您可以将这些范围内的常规 space 替换为 no-break space 这样的

for range in backgroundRangeArray {
    text = text?.replacingOccurrences(of: " ", with: "\u{00a0}", options: .caseInsensitive, range: range)
}