Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a circular NSButton?

I am trying to create a custom shape NSButton. In particular I am trying to make a round button, using a custom image. I've found a tutorial on the creation of custom UIButton and tried to adapt it to NSButton. But there's a huge problem. clipsToBounds seems to be iOS only(

Here's my code:

import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var mainButton: NSButton!
    var size = 32

    override func viewDidLoad() {
        super.viewDidLoad()
        configureButton()
                // Do any additional setup after loading the view.
    }
    func configureButton()
    {
        mainButton.wantsLayer = true
        mainButton.layerContentsRedrawPolicy = NSViewLayerContentsRedrawPolicy.OnSetNeedsDisplay
        mainButton.layer?.cornerRadius = 0.5 * mainButton.bounds.size.width
        mainButton.layer?.borderColor = NSColor(red:0.0/255.0, green:122.0/255.0, blue:255.0/255.0, alpha:1).CGColor as CGColorRef
        mainButton.layer?.borderWidth = 2.0
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

What am I doing wrong? How can I make a circular NSButton? Can you suggest anything on replacing clipsToBounds?

Because here is what I was able to get so far:

enter image description here

like image 730
Anna-Lischen Avatar asked Mar 03 '16 19:03

Anna-Lischen


2 Answers

NSButton is a subclass of NSView, so all methods in NSView, such as drawRect(_:), are also available in NSButton.

So create a new Button.swift which you draw your custom layout

import Cocoa

class Button: NSButton {

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        // Drawing code here.
        let path = NSBezierPath(ovalIn: dirtyRect)
        NSColor.green.setFill()
        path.fill()
    }

}

enter image description here

Great Tutorial Here. It is iOS , but quite similar!

like image 162
Willjay Avatar answered Sep 23 '22 16:09

Willjay


Don't play around with corner radius. A circle doesn't have corners. To make the button appear as a circle, mask the button's layer to a circle.

like image 29
matt Avatar answered Sep 23 '22 16:09

matt