How to connect outlets and actions in Swift / MacOS programaticly

帅比萌擦擦* 提交于 2019-12-02 00:25:42

问题


I have a simple example. I connected the left button1 and label1 with ctrl-draging it to the contollerclass.

How can I do the same for the right button2 label2 programaticly (without ctrl-draging)

That´s my code:

class ViewController: NSViewController {

  @IBOutlet weak var label1: NSTextField!  //connected with ctrl-drag
  @IBOutlet weak var button1: NSButton!    //connected with ctrl-drag

  @IBOutlet weak var label2: NSTextField!  //not yet connected
  @IBOutlet weak var button2: NSButton!    //not yet connected

  @IBAction func button1Pressed(_ sender: Any)  //connected with ctrl-drag
  { label1.stringValue = "button-I"
    button1.title = "pressed"
  }

  @IBAction func button2Pressed(_ sender: Any)  //not yet connected
  { label2.stringValue = "button-II"
    button2.title = "pressed"
  }
  override func viewDidLoad() {
    super.viewDidLoad()
  }
}

回答1:


If you want to use storyboard and lay out all your elements there, you can't really avoid the ctrl drag (or just drag if you open the connections inspector on the right).

You could however create your second button programmatically in code and not use the storyboard at all for it. Then programmatically add your constraints too.

You can also add the action of the button programmatically (using addTarget) if you would like but that would require at least the IBOutlet to be setup in order to have a reference to the button.



来源:https://stackoverflow.com/questions/44162445/how-to-connect-outlets-and-actions-in-swift-macos-programaticly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!