如何以编程方式连接Swift/MacOS中的插座和动作 [英] How to connect outlets and actions in Swift / MacOS programaticly

查看:108
本文介绍了如何以编程方式连接Swift/MacOS中的插座和动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的例子. 我通过ctrl将左button1和label1连接到contoller类.

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

如何以编程方式(不使用ctrl拖动)对右边的button2 label2进行相同操作

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

那是我的代码:

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()
  }
}

推荐答案

如果要使用情节提要并在其中布置所有元素,则无法真正避免ctrl拖动(如果打开连接检查器,则只能拖动ctrl)在右侧).

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.

如果您愿意,还可以通过编程方式(使用addTarget)添加按钮的动作,但这至少需要设置IBOutlet才能引用该按钮.

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.

这篇关于如何以编程方式连接Swift/MacOS中的插座和动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆