Anna-Lischen
Anna-Lischen

Reputation: 878

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

Upvotes: 6

Views: 2972

Answers (3)

Willjay
Willjay

Reputation: 6459

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!

Upvotes: 8

matt
matt

Reputation: 535315

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.

Upvotes: 6

Spinnaker
Spinnaker

Reputation: 346

You are setting the radius based upon the width of the button. By the look of your screenshot, the button is not a square when you start, so rounding the corners cannot create a circle.

Upvotes: 3

Related Questions