当将Swift代码与Storyboard相连接时,如何添加IBAction
和IBOutlet
标签?
当将Swift代码与Storyboard相连接时,如何添加IBAction
和IBOutlet
标签?
为变量和函数添加IBAction
和IBOutlet
属性,以便它们可以在界面构建器中可见。
class ViewController: UIViewController {
@IBOutlet var label: UILabel?
@IBAction func doTap(x:UIButton) {
println("Tapped: \(x)")
}
}
@IBDesignable
和@IBInspectable
。 :) - akashivskyy@IBOutlet weak var label: UILabel!
吗? - TheTiger以下代码展示了Swift中的IBOutlet和IBAction格式:
class MyViewController: UIViewController {
@IBOutlet weak var btnSomeButton: UIButton?
@IBOutlet weak var lblLabelItem: UILabel?
@IBAction func btnSomeButtonClicked(sender: UIButton) {
...
}
}
你可以像在 Objective-C 中一样绑定它们。
我更倾向于Jayprakash的答案,而不是得到了更多赞的第一个答案。唯一需要纠正的是将IBOutlets标记为隐式解包的!
。在Swift的最新版本中,与IB交互的方式发生了几个变化,因此第一个答案不再正确。在Swift中,IBOutlets不再具有任何隐式行为或魔法——它们只是用于IB的注释。截至本回答日期,以下代码是正确的:
// How to specify an the equivalent of IBOutletCollection in Swift
@IBOutlet var fields: [UITextField]!
// How to specify a standard IBOutlet
@IBOutlet weak var button: UIButton!
// How to specify an IBAction
@IBAction func buttonWasPressed(sender: UIButton) { ... }
IBOutlet
。
以下代码为您说明如何将IBOutlet
添加到UILabel
中。
class ViewController: UIViewController {
@IBOutlet var label : UILabel
}