Creating a UIToolbar in Swift 3

4.6k views Asked by At

How do you create a UIToolbar in Swift 3? I want an action on the left and action on the right and the title in the middle like most apps do. It also looks like a navigation controller without the back action arrow or stack.

The code is something like this:

let buttona = UIBarButtonItem(title: "Buttona", style: .plain, target: self, action: #selector(buttonaToolbar(sender:)));
let buttonb = UIBarButtonItem(title: "Buttonb", style: .plain, target: self, action: #selector(buttonbToolbar(sender:)));

let title = UILabel();

toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 44));
1

There are 1 answers

0
Shibili k.p On

Here is the way to make a toolbar with two buttons and title in the middle Using swift 3 :

func createToolbar(){
// ToolBar
    let toolBar = UIToolbar()
    toolBar.barStyle = .blackTranslucent
    toolBar.isTranslucent = true 
    toolBar.backgroundColor = UIColor.blue
    toolBar.tintColor = UIColor.white
    toolBar.sizeToFit()
    // Adding Button ToolBar
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(EnqiryViewController.doneClick))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(YourViewContreoller.cancelClick))
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.isUserInteractionEnabled = true
}

Now the write the functions for the actions:

func doneClick() {
   //do something here
}

func cancelClick() {
   //do something here
}