Search code examples
macoscocoansattributedstringnsbuttonnsbuttoncell

NSAttributedString size() method returns incorrect width


I created a custom NSButtonCell subclass which allows customizing padding between a button's contents. In my implementation (the full source code can be found on GitHub) I override titleRect(forBounds:) to position the button title:

var titleSize: NSSize {
    return NSSize(width: ceil(attributedTitle.size().width),
                  height: ceil(attributedTitle.size().height))
}

override func titleRect(forBounds rect: NSRect) -> NSRect {
    return CGRect(x: paddingLeft,
                  y: rect.height / 2 - titleSize.height / 2,
                  width: titleSize.width,
                  height: titleSize.height)
}

The result doesn't look good:

enter image description here

To get the desired outcome I have to add an extra padding to the width: enter image description here

I also tried using boundingRect(with:options:context:) to get the size, but I got the same results.


Solution

  • For future reference: I figured out the issue. When using attributedTitle, it's important to specify the font of the button, so that attributedString.size() can calculate the necessary width correctly. I assumed that by default, calculations are based on the default font for NSButton but apparently that was incorrect. See my commit for more details.