Search code examples
swiftuitoolbar

Evenly space UIToolbar buttons in inputAccessoryView


In the following code I have three buttons that show when an inputField is tapped. Right now the buttons show but all of them are shifted to the left and what I would like to do is have them evenly space and keep them like that regardless of what phone size they are viewed on.

How can I evenly space the buttons in a UIToolbar?

CODE:

override func viewDidLoad() {
    super.viewDidLoad()

    addButtonsToKeyboard()
}


 // Reusable Button
func configurButton(button:UIButton) {
    button.backgroundColor = UIColor.whiteColor()
    button.layer.cornerRadius = 5
    button.layer.borderWidth = 1.0
    button.layer.borderColor = UIColor.blueColor().CGColor
    button.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
    button.setTitleColor(UIColor.blueColor(), forState: .Highlighted)
    button.frame = CGRect(x:0, y:0, width:50, height:35)
    button.addTarget(self, action: #selector(customKeyPressed), forControlEvents: UIControlEvents.TouchUpInside)
}


   func addButtonsToKeyboard(){
        // First button
        let button1 = UIButton()
        button1.setTitle("Btn 1", forState: .Normal)
        configureButton(button1)
        let barButton1 = UIBarButtonItem()
        barButton1.customView = button1

        // Second button
        let button2 = UIButton()
        button2.setTitle("Btn 2", forState: .Normal)
        configureButton(button2)
        let barButton2 = UIBarButtonItem()
        barButton2.customView = button2

        // Third button
        let button3 = UIButton()
        button3.setTitle("Btn 3", forState: .Normal)
        configureButton(button3)
        let barButton3 = UIBarButtonItem()
        barButton3.customView = button3


        /**
         *   UIToolbar.
         */
        let toolBar = UIToolbar()
        toolBar.tintColor = UIColor.redColor()
        toolBar.barTintColor = UIColor.lightGrayColor()

        toolBar.items = [barButton1, barButton2, barButton3]
        toolBar.sizeToFit()

        myInputField.inputAccessoryView = toolBar
    }


    func customKeyPressed(sender: UIButton){
        // do something
    }

CURRENT:

enter image description here

AFTER:
enter image description here


Solution

  • Very simple, you just need to add a flexible bar button item between each button. See the following:

    let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    toolbar.items = [barButton1, space, barButton2, space, barButton3]