Search code examples
swiftmacosnsbutton

create nsbutton manually - call function


This question probably is trivial but I am searching for hours now and just dont find the fitting link.

I am programming a board game with many fields like a chess board. I managed to create all fields as buttons with for ... in and code like this:

let feld = NSButton()
feld.frame = CGRect(x: 1300+30*h, y: 20, width: 22, height: 22)
feld.image = NSImage(named: NSImage.Name("Mulleimer"))
arrayOfButtons.append(feld)

When a button is pressed I want to start a function. How to do this!? I only found code for C++ and Ios but not for Swift Macos. For example this one was given for Ios but I dont know how to change it to MacOS:

feld.Target(self, action: #selector(ButtonReiheDeaktivieren), for: .touchUpInside)

Solution

  • You can add target and action like this:

    fled.target = self
    fled.action = #selector(ButtonTest)