Adrian Ruth Adrian Ruth - 9 days ago 9
iOS Question

Custom UIToolBar using xib [Swift 3]

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?

Answer

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