When hooking Swift code up to a Storyboard, how do you add the IBAction
and IBOutlet
tags?
Add IBAction
and IBOutlet
attributes to variables and functions so they can be visible in Interface builder.
class ViewController: UIViewController {
@IBOutlet var label: UILabel?
@IBAction func doTap(x:UIButton) {
println("Tapped: \(x)")
}
}
@IBDesignable
and @IBInspectable
if you're developing your own controls. :) –
Castorina @IBOutlet weak var label: UILabel!
? –
Dropforge Below code shows IBOutlet and IBAction format in Swift :
class MyViewController: UIViewController {
@IBOutlet weak var btnSomeButton: UIButton?
@IBOutlet weak var lblLabelItem: UILabel?
@IBAction func btnSomeButtonClicked(sender: UIButton) {
...
}
}
You can bind them same way as done in Objective-C.
Just use old ctrl + drag technique which was popular in Xcode5 and everything works fine.
I would agree more with Jayprakash than the upvoted first answer. The only thing I would correct is the marking of the IBOutlets as implicitly unwrapped with the !
The first answer used to be correct, but several changes were made in Swift and how it interacts with IB in the latest release. In Swift, IBOutlets no longer have any implicit behavior or magic--they are simply annotations for IB. As of the date of this response, the following code is correct:
// 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) { ... }
While creating a project, you should have selected the storyboard, so that you can add your IBOutlet
's directly in the story board.
The Below code gives you a idea of how to add IBOutlet
to the UILabel
class ViewController: UIViewController {
@IBOutlet var label : UILabel
}
© 2022 - 2024 — McMap. All rights reserved.