简体   繁体   中英

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:

在此处输入图片说明

To get the desired outcome I have to add an extra padding to the width: 在此处输入图片说明

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM