我有一個簡單的例子。 我連接了左邊的按鈕1和label1並按住Ctrl鍵拖動到控制器類。如何在Swift/MacOS中編程式連接插座和動作
我怎樣才能做到同爲右按鈕2 LABEL2 programaticly(不按Ctrl-draging)
That's我的代碼:
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()
}
}
當您在代碼中創建它時,您不需要'IBAction'和'IBOutlet'。而且你不會在代碼中「按住Ctrl鍵」。您編寫實際的代碼來創建控件並分配操作方法。 – rmaddy
我想使用故事板來佈置所有元素,只有連接應該通過編程創建,但這似乎不起作用;-( – mica
你可以編寫代碼訪問故事板,然後訪問控件並將其分配給插座但爲什麼當你可以簡單地連接故事板中的插座時,你爲什麼要這麼做呢? – rmaddy