NSButton标题未垂直居中,但略低

时间:2018-06-22 10:55:27

标签: swift macos nsbutton

我是macOS编程的新手,这可能是一个愚蠢的问题,但这使我陷入困境。

我正在尝试将NSButton子类化,并创建一个更具可定制性的按钮类。除了标题没有垂直居中,从垂直中心向下偏移几个像素以更具体之外,其他所有内容都正常运行。

然后我发现,即使原生NSButton的标题也存在此“问题”。这是示例:

MDN docs

为了进行比较,我在左边放了一个普通的正方形 NSButton,右边是我自定义的NSButton,两个按钮的标题都比中心。

这是我的问题:

  1. 为什么会这样?
  2. 如何设置绝对居中的标题?

这是我用于设置可自定义标题的代码(如果您想知道的话):

我正在使用名为click me to view the image的库来设置attributedTtile,这就是为什么出现这些.withFont的原因。

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

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

1 个答案:

答案 0 :(得分:0)

这个答案可以帮助我,也许可以回答为什么会发生

Link

好吧,我在这里使用链接中引用的代码进行了测试,并获得了以下代码:

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
}

覆盖 NSButtonCell func titleRect(forBounds rect:NSRect)-> NSRect 。我能够集中文本。