1
votes

I'm new to macOS programming and this may be a silly question but it got me stuck.

I'm trying to subclass the NSButton and create a more customizable button class. Everything worked fine except the title which is not centered vertically, offset several pixels down from the vertical center to be more specific.

Then I found out that even the native NSButton's title also has this "problem". Here's the example:

click me to view the image

For comparison I put a normal square NSButton on the left, and the right one is my customized NSButton, and the titles in both buttons placed a little lower than the center.

So here's my questions:

  1. Why does this happen?
  2. How to set absolutely centered title?

Here's my code for setting the customizable title (in case you want to know):

I'm setting the attributedTtile using a library called SwiftyAttributes, that's why those .withFont stuff appear.

let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center

attributedTitle = title
  .withFont(.systemFont(ofSize: 13))
  .withParagraphStyle(paragraph)
  .withTextColor(titleColor)
1

1 Answers

1
votes

this answer help me and maybe answer Why does this happen:

Link

Well, I tested here using the code quoted in the link and got this code:

override func titleRect(forBounds rect: NSRect) -> NSRect {
    var theRect = super.titleRect(forBounds: rect)
    theRect.origin.y = rect.origin.y+rect.size.height-(theRect.size.height+(theRect.origin.y-rect.origin.y))-2;
    return theRect
}

Overriding the NSButtonCell func titleRect(forBounds rect: NSRect) -> NSRect I was able to centralize the text.