Create a NSButton in code (swift)

Some time ago I shared a simple way to create custom UIButtons in code. As I’m starting to polish NewsWave for Mac, I wanted the same ability to easily create custom buttons. So, I ported the function to macOS, feel free to leverage:

 

    func createNewNSButton(title: String, textSizeDelta: CGFloat?, textColor: NSColor?,  backgroundColor: NSColor?, cornerRadius: Bool, cornerColor: NSColor?) -> NSButton{

        

        let button = NSButton()

        

        button.translatesAutoresizingMaskIntoConstraints = false

        button.attributedTitle = NSMutableAttributedString(string: ”  \(title)  “, attributes: [NSAttributedString.Key.foregroundColor: (textColor ?? NSColor.white), NSAttributedString.Key.font: NSFont.systemFont(ofSize: (NSFont.systemFontSize + (textSizeDelta ?? 0)))])

       

        button.isBordered = false

        button.wantsLayer = true

        button.layer?.backgroundColor = backgroundColor?.cgColor ?? .clear

 

        if cornerRadius == true{

            button.layer!.masksToBounds = true

            button.layer!.cornerRadius = 22

            button.layer!.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMinYCorner]

            if cornerColor != nil{

                button.layer!.borderWidth = 2

                button.layer!.borderColor = cornerColor!.cgColor

            }

        }

        

        return button

    }

 

And to add an action you just:

button.action = #selector(whateverActionGoesHere)

Here’s an example of the types of buttons you can create:

Screen Shot 2020 04 04 at 16 49 02

Stay safe & until next time,

 

Marc

—-

 

 

Twitter -> @MarcMasVi