oldman
oldman

Reputation: 145

Swift 3 osx button.addTarget

xcode 8 swift 3 for OSX

I have code that creates button within myView.I would like to add an action to each of the buttons it creates. I believe you would normally use button.addTarget but this doesn't work for OSX Any ideas ?

thanks

import Cocoa

class MainWindowController: NSWindowController {

    var buttonArray: Array<NSButton> = []
    var buttonTitleArray: [String] = ["Answer1","Answer2","Answer3","Answer4"]
    @IBOutlet weak var myView: NSView!

    override func windowDidLoad() {
        super.windowDidLoad()

        var horizontalx = 50

        //Create button Array and tag buttons
        for i in 0..<buttonTitleArray.count{
            let button = NSButton(frame: NSRect(x: horizontalx, y: 50, width: 100, height: 50))
            button.tag = i
            buttonArray.insert(button, at: i)
            horizontalx = horizontalx + 100
        }

        //Adds Buttons to myView
        for i in 0..<buttonTitleArray.count{
            let button:NSButton = buttonArray[i]
            button.title = buttonTitleArray[i]
            myView.addSubview(button)
        }

        //Just for testing we can find tag
        for i in 0..<buttonTitleArray.count{
            let buttonFromArray = buttonArray[i]
            let tag = buttonFromArray.tag
            if (tag == 2){
                print("found Tag")
            }
        }

    }//EO Overide


}//EnD oF thE wORld

Upvotes: 2

Views: 1651

Answers (2)

electromaggot
electromaggot

Reputation: 675

I was just struggling with this, mainly with static methods, so I thought I'd chime in (late) and add to jlew's answer.

If you set button.action, also be careful how you set button.target, especially if you leave it nil. Remember that #selector is not a mere "function pointer" but an Objective-C method reference via an object (the target). Apple's Objective-C Target-Action page is very helpful on that.

Say you want to set up a "close" button. That's easy...

button = NSButton(title: "Exit", target: nil, action: #selector(window?.close))

...but now say you wish to intercept that call first before closing. You can piggy-back on your existing window object by doing this:

        button = NSButton()
        button.title = "Exit"
        button.action = #selector(window?.buttonPressed)
    }
}

extension NSWindow {
    func buttonPressed() {
        Swift.print("Clicked Exit button!")
        close()
    }
}

Again, the above of course for a target of nil. Otherwise, assign button.target to your @objc object containing your button handler.

Upvotes: 2

jlew
jlew

Reputation: 10591

In one of your loops:

button.action = #selector(buttonPressed)

Then:

func buttonPressed(button:NSButton) {
    print("Clicked \(button.title)!")
}

Upvotes: 2

Related Questions