Macos 以编程方式设置NSButton的颜色

Macos 以编程方式设置NSButton的颜色,macos,cocoa,swift,background-color,nsbutton,Macos,Cocoa,Swift,Background Color,Nsbutton,我使用以下代码以编程方式生成一些NSButton: for i in 1...height { for j in 1...width { var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30)) but.tag = k but.title = "" but.action = Selector("b

我使用以下代码以编程方式生成一些NSButton:

for i in 1...height {
        for j in 1...width {
            var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30))
            but.tag = k
            but.title = ""
            but.action = Selector("buttonPressed:")
            but.target = self
            but.bezelStyle = NSBezelStyle(rawValue: 6)!
            but.layer?.backgroundColor = NSColor.blackColor().CGColor

            var ges = NSClickGestureRecognizer(target: self, action: Selector("addFlag:"))
            ges.buttonMask = 0x2
            ges.numberOfClicksRequired = 1
            but.addGestureRecognizer(ges)

            ar.append(but)
            self.view.addSubview(but)
            x += 30
            k++
        }
        y += 30
        x = 0
    }

我需要将所有按钮的背景色设置为灰色或黑色(随机)。我不知道如何获取或设置
NSButton
背景色。我对swift编程非常陌生,我并不真正了解obj-c,所以如果您能在swift上编写它,我将非常感激

我通过NSButton参考指南阅读,看来改变它的唯一方法是改变图像。但我已经找到了一种使用颜色来创建图像的方法。将此扩展添加到类文件的顶部

extension NSImage {
class func swatchWithColor(color: NSColor, size: NSSize) -> NSImage {
    let image = NSImage(size: size)
    image.lockFocus()
    color.drawSwatchInRect(NSMakeRect(0, 0, size.width, size.height))
    image.unlockFocus()
    return image
   }
}
这将允许我们以后使用UICOLOR创建NSImage。最后,当你想要创建你的按钮时,使用我们制作的扩展设置图像

 myButton.image = NSImage.swatchWithColor( NSColor.blackColor(), size: NSMakeSize(100, 100) )
对于“大小”参数,将其设置为按钮的大小

更新*如果你想随机选择颜色,你可以这样做

 var randomIndex = arc4random_uniform(2) + 1 //Creates a random number between 1 and 2  
 var colour = NSColor() //Empty colour

    if randomIndex == 1 {

        //If the random number is one then the colour is black
        colour = NSColor.blackColor()
    }

    else {

        //Else if it's not one it's grey
        colour = NSColor.grayColor()
    }

    //set the button's image to the new colour
    myButton.image = NSImage.swatchWithColor(colour, size: //My button size)
要获取大小,请转到情节提要,单击按钮并转到标尺选项卡。这里显示了按钮的大小


坏消息是,没有给按钮上色的好方法;它们都有优点和缺点。 对于像我一样对优胜美地公司旗下的彩色按钮感到好奇的每个人,我写了一本可能不是彩色按钮的终极指南,但肯定是一个强有力的竞争者:

这涵盖了所有样式的按钮,并提供了几乎任何组合的屏幕截图,使用

  • 背景色
  • drawRect
  • 细胞背景色
  • 单色图层效果
  • 白平衡调整层效应
  • IB中设置的图像
  • 子类化NSButton并根据按钮状态添加图像

如果有人能想出另一种给按钮上色的方法,我很想听听

我是用这段代码做的

final class MyButton: NSButton {
    override func awakeFromNib() {
        let layer = CALayer()
        layer.backgroundColor = CGColorCreateGenericRGB(59.0/255, 52.0/255.0, 152.0/255.0, 1.0)
        self.wantsLayer = true
        self.layer = layer
    }
}

好的,下面是我在需要更改按钮外观时所做的:将其子类化

//
//  LSButtonColor.swift
//
//  Created by Lloyd Sargent on 8/26/16.
//  Copyright © 2016 Canna Software. All rights reserved.
//  License: Permission is hereby granted, free of charge, to any 
//           person obtaining a copy of this software and associated
//           documentation files (the “Software”), to deal in the 
//           Software without restriction, including without
//           limitation the rights to use, copy, modify, merge, 
//           publish, distribute, sublicense, and/or sell copies of 
//           the Software, and to permit persons to whom the Software 
//           is furnished to do so, subject to the following
//           conditions:
//           
//           The above copyright notice and this permission notice
//           shall be included in all copies or substantial portions
//           of the Software.
//
//           THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF
//           ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//           TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
//           PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
//           SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//           CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//           OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
//           IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//           DEALINGS IN THE SOFTWARE.
//

import Cocoa

class LSButtonColor: NSButton {

fileprivate struct AssociatedKeys {
    static var variableDictionary = "ls_variableDictionary"
}

fileprivate var variableDictionary: [String:AnyObject]! {
    get {
        var localVariableDictionary = objc_getAssociatedObject(self, &AssociatedKeys.variableDictionary) as! [String:AnyObject]!
        if localVariableDictionary == nil {
            localVariableDictionary = [String:AnyObject]()
            objc_setAssociatedObject(self, &AssociatedKeys.variableDictionary, localVariableDictionary, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        return localVariableDictionary
    }
    set(updatedDictionary) {
        objc_setAssociatedObject(self, &AssociatedKeys.variableDictionary, updatedDictionary, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
}

var backgroundColor: NSColor! {
    get {
        return variableDictionary["backgroundColor"] as? NSColor
    }
    set(newBackgroundColor) {
        var localVariableDictionary = variableDictionary
        localVariableDictionary?["backgroundColor"] = newBackgroundColor
        variableDictionary = localVariableDictionary
    }
}

var altBackgroundColor: NSColor! {
    get {
        return variableDictionary["altBackgroundColor"] as? NSColor
    }
    set(newAltBackgroundColor) {
        var localVariableDictionary = variableDictionary
        localVariableDictionary?["altBackgroundColor"] = newAltBackgroundColor
        variableDictionary = localVariableDictionary
    }
}

var borderColor: NSColor! {
    get {
        return variableDictionary["borderColor"] as? NSColor
    }
    set(newBorderColor) {
        var localVariableDictionary = variableDictionary
        localVariableDictionary?["borderColor"] = newBorderColor
        variableDictionary = localVariableDictionary

        self.layer?.borderColor = newBorderColor.cgColor
    }
}

var cornerRadius: CGFloat {
    get {
        return variableDictionary["cornerRadius"] as! CGFloat
    }
    set(newCornerRadius) {
        var localVariableDictionary = variableDictionary
        localVariableDictionary?["cornerRadius"] = newCornerRadius as AnyObject?
        variableDictionary = localVariableDictionary

        self.layer?.cornerRadius = newCornerRadius
    }
}

var borderWidth: CGFloat {
    get {
        return variableDictionary["borderWidth"] as! CGFloat
    }
    set(newBorderWidth) {
        var localVariableDictionary = variableDictionary
        localVariableDictionary?["borderWidth"] = newBorderWidth as AnyObject?
        variableDictionary = localVariableDictionary

        self.layer?.borderWidth = newBorderWidth
    }
}

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)

    // Drawing code here.
    if self.isHighlighted {
        if self.layer != nil {
            self.layer?.backgroundColor = self.altBackgroundColor.cgColor
        }
    }
    else {
        if self.layer != nil {
            self.layer?.backgroundColor = self.backgroundColor.cgColor
        }
    }
  }
}
好的,你可能会困惑的第一件事是
objc_getAssociatedObject
-最初我是作为一个类别来做的,这是一种简单的向类别中添加变量的方法(每个人都说你做不到,但每个人都没有意识到,是的,你可以-这并不明显)

不幸的是,我遇到了一些问题,所以我只是把它做成了一个类,而没有费心去掉关联的对象(为什么要搞砸成功?)


无论如何,您应该能够拉出相关代码来更改任何按钮的背景。

非常感谢,我知道如何随机选择颜色,但第一部分很棒!很高兴帮助你:)我的道歉-网站被黑客入侵,我不得不重新安装内容;很抱歉错过了这个链接。链接仍然是死的。时间安排不好-网站再次被黑客攻击,我正在转移到一个更安全的提供商;此操作完成后将立即更新。(Wordpress到底是什么吸引了源源不断的黑客?)!(我已经为macOS 10.11和故事板更新了这个)。