I'm running across this issue which I can't seem to find the answer to online. Basically what I'm trying to do is programmatically create a UIToolbar
with some UIBarButtonItems
.
What I've done (as detailed below) is create the UIToolbar
and then set the items of the UIToolbar
to an array holding all the UIBarButtonItems
I want.
Unfortunately, though the UIToolbar
shows up, the UIBarButtonItems
have yet to show themselves
Any suggestions or explanations as to why this is happening is much appreciated!
class DrawViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create bar buttons
let deleteBarButton = UIBarButtonItem(image: UIImage(named: "greyDelete"), style: .Plain, target: self, action: "deleteView:")
let eraseBarButton = UIBarButtonItem(image: UIImage(named: "greyErase"), style: .Plain, target: self, action: "erase:")
let resizeBarButton = UIBarButtonItem(image: UIImage(named: "greyResize"), style: .Plain, target: self, action: "resize:")
let viewBarButton = UIBarButtonItem(image: UIImage(named: "greyView"), style: .Plain, target: self, action: "view:")
let colorBarButton = UIBarButtonItem(image: UIImage(named: "greyColor"), style: .Plain, target: self, action: "color:")
let drawBarButton = UIBarButtonItem(image: UIImage(named: "greyDraw"), style: .Plain, target: self, action: "draw:")
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
//set up toolbar
let toolbarItems = [deleteBarButton, flexibleSpace, eraseBarButton,
flexibleSpace, resizeBarButton, flexibleSpace,
viewBarButton, flexibleSpace, colorBarButton,
flexibleSpace, drawBarButton]
let toolbar = UIToolbar(frame: CGRectMake(0, view.bounds.height*0.93, view.bounds.width, view.bounds.height*0.7))
toolbar.barTintColor = UIColor(patternImage: UIImage(named: "blueToolbar")!)
toolbar.setItems(toolbarItems, animated: true)
self.view.addSubview(toolbar)
}
I would imagine the problem is the curious way you're creating the
UIToolbar
. This line here seems deeply suspect:Why make it 0.7 times the height of your view?
To fix this problem, create the toolbar either without the frame constructor or with
CGRectZero
for its frame. Then usesizeToFit()
to make it the appropriate size.A simpler alternative, if possible, is to use a
UINavigationController
and tell it to show its own toolbar. You can then fill that by setting your view controller'stoolbarItems
property to your array, and it will all work without you having to create, position or manage aUIToolbar
at all.