Adding buttons to toolbar programmatically in swift
None of the above worked for me, but:
Swift 3 / Swift 4
self.navigationController?.isToolbarHidden = falsevar 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 functionself.toolbarItems = items // this made the difference. setting the items to the controller, not the navigationcontroller
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 = falsevar items = [UIBarButtonItem]()items.append( UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))items.append( UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(onClickedToolbeltButton(_:))))toolbarItems = items
self.navigationController?.toolbarItems = itemsself.navigationController?.setToolbarItems(items, animated: false)self.navigationController?.toolbar.setItems(items, animated: false)
Try it.
self.navigationController?.toolbarHidden = false var items = [UIBarButtonItem]() items.append( UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil) ) items.append( UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "onClickedToolbeltButton:") ) self.navigationController?.toolbar.setItems(items, animated: false)