Search code examples
swiftuilabelnsattributedstring

NSBackgroundColorAttributeName doesn't seem to work on iOS 10.3


We display a label in our apps which contains attributed text and some highlighting color. To achieve this, we use the following code which used to work:

let paddedLineAttributed = NSMutableAttributedString(string: paddedLine, attributes: [NSFontAttributeName : newFont, NSParagraphStyleAttributeName : paragraphStyle, NSBackgroundColorAttributeName : color])

But after upgrading one of our test devices to iOS 10.3, the specified background color for the label is not taking effect anymore. Instead, it was using a transparent background color making the label invisible as we are using a white text color which is the same color as the parent view.

I suspect that the NSBackgroundColorAttributeName is the culprit but the official API Reference remains unchanged - https://developer.apple.com/reference/appkit/nsbackgroundcolorattributename

Any ideas?


Solution

  • Copied from @schystz comment:

    Adding NSBaselineOffsetAttributeName: 0 resolves the issue.

    let paddedLineAttributed = NSMutableAttributedString(string: paddedLine, attributes: [NSFontAttributeName : newFont, NSParagraphStyleAttributeName : paragraphStyle, NSBackgroundColorAttributeName : color, NSBaselineOffsetAttributeName: 0])