Aaron Aaron - 1 month ago 11
iOS Question

How do you assign an IBOutlet programmatically using Swift?

I added a bar button item programmatically to a view controller:

override func viewDidLoad() {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Menu", style: .Plain, target: nil, action: nil)

Now I want to assign that bar button item to an
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() {
        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.