Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView correctly highlight words

I'm trying to highlight a couple of words from textView with rounded rects. And it all seems good, except for the line breaks where I get unexpected behaviour.

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()
        }
    }
}

enter image description here (note the unwanted space between special characters)

like image 551
HelloimDarius Avatar asked Feb 19 '26 10:02

HelloimDarius


1 Answers

If I got it right, you have ranges of string that you want to be on the same line. If so, you can replace a regular space in these ranges with a no-break space like that

for range in backgroundRangeArray {
    text = text?.replacingOccurrences(of: " ", with: "\u{00a0}", options: .caseInsensitive, range: range)
}
like image 144
Yury Imashev Avatar answered Feb 22 '26 00:02

Yury Imashev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!