Search code examples
macoscocoaswiftbackground-colornsbutton

Set color of NSButton programmatically swift


I generate some NSButtons programmatically with this code:

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
    }

And I need to set the background color of all buttons to gray or black (randomly). I have no idea how to get or set the NSButton background color. I'm quite new to swift programming and I don't really know obj-c, so if you'll write it on swift, I'll really appreciate it!


Solution

  • I read throgh the NSButton reference guide, And it seems that the only way to change it it changing the image. But I have gotten a way to create an image using a colour. Add this extionsion at the top of your class file

    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
       }
    }
    

    This will allow us to later create NSImage's using a UIColour. Lastly, When you want to create your button, Set the image using the extension we made.

     myButton.image = NSImage.swatchWithColor( NSColor.blackColor(), size: NSMakeSize(100, 100) )
    

    For the size parameter set it to your button's size.

    UPDATE* If you want to randomly choose the colour you can do this..

     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)
    

    To get the size go to your storyboard, click on your button and go to the ruler tab. There it shows your button's size.