I added a bar button item programmatically to a view controller:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Menu", style: .Plain, target: nil, action: nil)
}
Now I want to assign that bar button item to an IBOutlet
programmatically. How would I do that using Swift?
The IB
of IBOutlet
stands for Interface Builder and it represents a connection from the interface builder to the source code. Assigning an IBOutlet
programmatically couldn't make less sense.
An IBOutlet
is simply an instance variable of a class which is tied to part of the interface or can be set via the interface builder. If we want a reference to our button (in the same way we'd have a reference to it if we made it in the interface builder), we simply add a property to our class, and then assign our newly created button to that:
class MyViewController: UIViewController {
var someBarButton: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
self.someBarButton = UIBarButtonItem(title: "Menu", style: .Plain, target: nil, action: nil)
self.navigationItem.leftBarButtonItem = self.someBarButton
}
}
And now, someBarButton
is our "IBOutlet".
Some notes...
There's a pretty decent chance we might not actually want to do things this way.
This creates an extra strong reference to the button (self.navigationItem
already holds a strong reference to its leftBarButtonItem
).
You'll notice, if you make an IBOutlet
from interface builder, it is set up as a weak
property. So perhaps we want a weak property?
But we can actually do ourselves one better. Try this on for size:
var leftNavBarButton: UIBarButtonItem? {
get {
return self.navigationItem.leftBarButtonItem
}
set (newValue) {
self.navigationItem.leftBarButtonItem = newValue
}
}
Now, self.leftNavBarButton
is essentially just a convenient way of accessing self.navigationItem.leftBarButtonItem
.
You mean to assign an action to the button in code instead of in IB. Your question is worded in a somewhat confusing way, but never mind.
You use the target
and action
arguments of the UIBarButtonItem
constructor. target
is your controller, typically self
; action
is a string that is a selector signature of your button handler contained by that controller.
self.someBarButton = UIBarButtonItem(title: "Menu", style: .Plain,
target: self, action: "buttonHandler:")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With