代码之家  ›  专栏  ›  技术社区  ›  Z S

按钮:蓝色背景

  •  0
  • Z S  · 技术社区  · 4 年前

    我想让我的NSButton看起来像Xcode的提交按钮 Xcode commit button

    但似乎没有任何方法可以轻松更改NSButton的背景色。您必须将“边框”更改为“否”,然后设置按钮的背景色,并为按钮设置“attributedTitle”,使文本颜色变为白色。但当我这么做的时候,结果看起来一点也不接近:

    enter image description here

    按钮没有任何阴影;文本看起来不居中;它也不支持在选择按钮时更改背景颜色,就像Xcode中的按钮一样。

    这肯定很容易复制,因为我相信我在整个系统中都见过类似的按钮。

    下面是我为此编写的NSButton子类:

    override func awakeFromNib() {
        super.awakeFromNib()
        self.wantsLayer = true
        self.isBordered = false //Important
        self.layer?.backgroundColor = backgroundColor.cgColor
        self.layer?.cornerRadius = 6.0
        
        let font = NSFont.systemFont(ofSize: 14, weight: .medium)
        let fontColor = NSColor.white
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center
    
        self.attributedTitle = NSAttributedString(string: self.title, attributes: [NSAttributedString.Key.foregroundColor : fontColor,
            NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle : paragraphStyle]) // to update text, have to update the attributeString's mutableString property
    }
    

    我很想知道我的错误在哪里。我本以为我需要一个带有边框和阴影效果的常规“按钮”,但背景是蓝色的,但从我所看到的情况来看,这似乎并不太好。

    谢谢

    0 回复  |  直到 4 年前
        1
  •  0
  •   Z S    4 年前

    因此,我找到了我一直在寻找的“简单”解决方案:无需对NSButton层进行任何调整。您只需将键设置为与“return”键等效的键!

    [self.editButton setKeyEquivalent: @"\r"];
    

    这将按钮的背景色设置为蓝色,并按照我的期望工作。如果你想要其他背景色,我想你必须像上面那样定制按钮。

    推荐文章