0

Can I create a custom UIToolBar in a Xib file?

I am wanting to make a toolbar with a done button on the far left and a last/next button set on the left side. But I want to make sure that the constraints are such that it will scale correctly for each phone size. Is there an example?

Sanoj Kashyap
  • 5,020
  • 4
  • 49
  • 75
rutheferd
  • 99
  • 1
  • 10
  • Just wanted to add this link, I messed up a couple times and had to do this to get everything running right. http://stackoverflow.com/questions/29923881/could-not-insert-new-outlet-connection-could-not-find-any-information-for-the-c – rutheferd Dec 01 '16 at 19:16

1 Answers1

3

Yes you can. First choose a xib as a template. Name the template "toolbar". create the xib

Then delete the default view it gives you. Go to the objects library in the bottom right hand corner and drag out a Toolbar. drag out a toolbar xib

You will get a default Bar Button Item on the far left. Rename this to "Done" then drag out another bar button item and rename it "Next" or "Last". rename bar button items

Now, create a new file. Choose Cococa Touch Class and make it a subclass of UIToolBar. enter image description here

Go back to your tool bar xib and make its class the Cocoa Touch class you just created. In my example, I named mine ToolBarExample.

Now go to your ViewController class. In the ViewDidLoad add the following.

   override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let toolBar = UINib(nibName: "toolbar", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! ToolBarExample

    toolBar.frame = CGRect(x: 0, y: self.view.frame.size.height - 46, width: self.view.frame.size.width, height: 46)

    toolBar.sizeToFit()

    view.addSubview(toolBar)

}

You can change change the scale, size and position of the toolbar by adjusting its frame. You can also adjust the toolbar xib and its bar button items from the Atrributes and Size Inspector. The final product of this example should be as follows in the Simulator.

Final Product in Simulator

gwinyai
  • 2,560
  • 2
  • 15
  • 17