2

I have an NSTextBlock subclass that has a specific backgroundColor set. Now when I add a custom paragraph style to a range of text like this

let block = MyTextBlock()
block.backgroundColor = myBackgroundColor

let pstyle = NSMutableParagraphStyle()
pstyle.textBlocks = [block]

attributedText.addAttribute(.paragraphStyle, value: pstyle, range: textRange)

// Append the attributed string to the text views textStorage ...

the text block is shown without a background color. I know that the text blocks works, because rectForLayout gets called, but when I try to override drawBackground it never gets called.

Do I have to do something else for NSTextBlocks to draw their background?

PS: Borders also seem to be ignored. I also tried to find a sample on Github, but that also doesn't draw any backgrounds, despite having a background color set.

1 Answers1

2

After trying everything, I finally managed to get the background to show up, by setting

setValue(100, type: .percentageValueType, for: .width)

It seems that the drawing logic expects some value for the content size. Really nice documentation job there. This requirement is nowhere to be found.

  • Thanks for this – I gave up working with NSTextBlocks after not being able to set the background, even though it seemed possible. Will give it another try now. – Tritonal Sep 14 '20 at 20:53