objective-cswiftcocoanstextviewtextkit

NSTextBlock backgroundColor is not drawn


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.


Solution

  • 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.