Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61774

Why UIBarbuttonItem is not working in Swift while code is written well?

I have written the same behaviour in two ways. The first one, doesn't work:

var barbutton = (left) ? navigationItem.leftBarButtonItem : navigationItem.rightBarButtonItem
barbutton = UIBarButtonItem(customView: button)

opposite to:

if (left) {
     navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
} else {
     navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}

What is the difference?

Upvotes: 0

Views: 437

Answers (1)

David Berry
David Berry

Reputation: 41226

As @Martin points out, the two code sequences are very different in function.

The first sets barbutton to the contents of either leftBarButtonItem or rightBarButtonItem and then discards that value and sets (the temporary variable) to a newly created button.

The second sets either leftBarButtonItem or rightBarButtonItem, depending on left to a newly created button.

There really isn't much way to shorten your code and still achieve the desired effect (without also obscuring the code).

You could use:

(left ? navigationItem.setLeftBarButtonItem : navigationItem.setRightBarButtonItem)(UIBarButtonItem(customView: button), animated: false)

But that's just weird.

Upvotes: 3

Related Questions