Assigning a button’s action – with added bug

This thoroughly spoilt my day today. I was convinced I’d gotten the ‘assign-an-action-on-the-fly’ code correctly, but it just Would. Not. Work. Turns out, I had gotten it right.

0) Create a new macOS application. Create a new NSViewController subclass, call it ‘EmbedController’; set it as the class of the initial view controller. Add one button to it, and add the following code:

class EmbedController: NSViewController {

  override func viewDidLoad() {

        super.viewDidLoad()

        testButton.action = #selector(EmbedController.simpleTest(sender:))

         }

@IBAction func simpleTest(sender: NSButton){

print(“This is a test”)

}

@IBOutlet weak var testButton: NSButton!

}

Connect the IBOutlet to the button; do NOT connect the IBAction.

Build and run. The button’s action gets assigned in viewDidLoad; if you press the button, “This is a test” will appear in the console.

1) Disconnect the EmbedController from the window. Create a new ViewController scene, add a container view, and create an embed segue from the containerView to the EmbedController.

Build and run. The button does nothing at all.

2) Add another IBAction to the button and connect it in IB:

    @IBAction func actionToOverride(_ sender: NSButton) {

        print("This should not be visible")

    }

Build and run again. This time, simpleTest fires and “This is a test” appears in the console.

My best bet is that setting an action in InterfactBuilder causes the button to be created slightly earlier so that the action gets assigned correctly? Or something along those lines?

3) As a bonus, I have tested this with other forms of embedding: NSTabViewController, NSSplitViewController – the behaviour is consistent. If you want to set an action in code, you need to have an action connected in IB.

责编内容来自:Extelligent Cocoa (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Assigning a button’s action – with added bug

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录