Swift UIToolbar positioning

812 Views Asked by At

I have a UIToolbar, but I have no idea how to positioning it..

I would add UIBarButtonItems to it, and positioning them. The toolbar showing up, but i can't change it size, and i can't position the buttons in it.

override func viewDidAppear(animated: Bool) {       
    self.navigationController?.setToolbarHidden(false, animated: true)
    self.navigationController?.toolbar.frame = CGRectMake(50, 50, 50, 50)
    self.navigationController?.toolbar.sizeToFit()

    let plusImg = UIImage(named: "navbar_icon-02.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)        
    let plusButton = UIBarButtonItem(image: plusImg, style: UIBarButtonItemStyle.Plain, target: self, action: "postLeft:")        
    let filterButton = UIBarButtonItem(title: "Feed filter", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
    let leftButton = UIBarButtonItem(title: "Button 3 tst", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)

    var toolbarButtons = [filterButton]
    toolbarButtons.append(plusButton)
    toolbarButtons.append(leftButton)

    self.toolbarItems = toolbarButtons
}
1

There are 1 best solutions below

3
matt On

There are two possible problems you might be having (I can't quite tell, from the way you've asked the question).

  • One problem might be that you are not in a navigation interface - you simply have a "loose" toolbar. Thus, the toolbar referred to through self.navigationController? is not your toolbar, and setting self.toolbarItems has no effect - those things are only for when you are in a navigation interface and the toolbar in question is the navigation controller's toolbar.

  • The other problem might be that you are in a navigation interface, in which case the toolbar position is not up to you - it's up to the navigation controller, which will always place it at the bottom of the screen.

So, either you need to be in a navigation interface so that the toolbar is the navigation controller's toolbar (and then your code will work, except for the positioning part), or else you can use a "loose" tolbar, in which case you need your code to refer to your toolbar, in which case you are free to position it, and you can give it items by setting its items.