8

How do I add padding to a substring of UITextView that is a NSMutableAttributedString (shown here highlighted in yellow)?

enter image description here

I currently have the attributed text (image 2) without any padding around the attributed text, but need to add some padding to it (image 3), which is some spacing around the highlighted text only (not the entire UITextView.

Here is a close-up comparing how the NSMutableAttributedString with/without padding (this padding should not apply to the rest of the text which unattributed):

enter image description here

Here's how I'm currently getting the text from the UITextView (after finding the range of text I want to highlight and storing the attributed text in attributedText):

var highlightedText = NSMutableAttributedString(string: "this text is highlighted")
let highlightedRange = NSRange(location: 0, length: highlightedText.characters.count)

highlightedText.addAttribute(NSBackgroundColorAttributeName,
                             value: UIColor.yellow, range: highlightedRange)

attributedText.replaceCharacters(in: highlightedRange, with: highlightedText)
user2560886
  • 1,910
  • 2
  • 14
  • 20

0 Answers0