【问题标题】:NSButton title not centered vertically but a little lowerNSButton 标题不是垂直居中而是稍微低一点
【发布时间】:2018-06-22 10:55:27
【问题描述】:

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

我正在尝试继承 NSButton 并创建一个更可定制的按钮类。除了标题没有垂直居中之外,一切正常,从垂直中心向下偏移几个像素以更具体。

然后我发现连原生NSButton的标题也有这个“问题”。示例如下:

click me to view the image

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

这是我的问题:

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

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

我正在使用名为SwiftyAttributes 的库设置attributedTtile,这就是出现.withFont 内容的原因。

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

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

【问题讨论】:

    标签: swift macos nsbutton


    【解决方案1】:

    这个答案对我有帮助,也许还能回答为什么会这样

    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 我能够集中文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      相关资源
      最近更新 更多