Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding buttons to toolbar programmatically in swift

Tags:

ios

swift

I'm having a hard time adding a button to the toolbar in swift, below you can see an image of the toolbar that I'm after, unfortunately even though I have it designed in my Storyboard file, it doesn't show up when setting the toolbar to be visible.

The way that I have designed this is two items, the first being a flexable space element, and the second being an add element. It looks like this:

enter image description here

Here's the code that I've used to attempt to replicate this in code:

self.navigationController?.toolbarHidden = false
self.navigationController?.toolbarItems = [UIBarButtonItem]()
self.navigationController?.toolbarItems?.append(
    UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
)
self.navigationController?.toolbarItems?.append(
    UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "onClickedToolbeltButton:")
)

As you can see I'm setting the toolbar to be visible, initializing (and clearing) the toolbarItems array of UIBarButtonItem, and then adding two UIBarButtonItem's to the array, in the proper order.

However, the toolbelt remains empty, why is this?

like image 219
Hobbyist Avatar asked Jan 30 '16 19:01

Hobbyist


2 Answers

None of the above worked for me, but:

Swift 3 / Swift 4

self.navigationController?.isToolbarHidden = false

var items = [UIBarButtonItem]()

items.append( UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) )
items.append( UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add)) ) // replace add with your function

self.toolbarItems = items // this made the difference. setting the items to the controller, not the navigationcontroller
like image 172
David Seek Avatar answered Nov 20 '22 02:11

David Seek


The usual way to do that is to create the array of toolbar items and then assign the array to the items property of the toolbar.

self.navigationController?.isToolbarHidden = false
var items = [UIBarButtonItem]()
items.append(
    UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
)
items.append(
    UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(onClickedToolbeltButton(_:)))
)
toolbarItems = items
like image 21
vadian Avatar answered Nov 20 '22 02:11

vadian