在inputAccessoryView中均匀空间UIToolbar按钮

时间:2016-11-07 13:09:30

标签: swift uitoolbar

在下面的代码中,我有三个按钮,显示何时点击inputField。现在按钮显示但是所有这些按钮都向左移动了,我想要做的就是让它们均匀分布空间,并保持它们像那样,无论它们在哪个手机上观看。

如何均匀分隔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
    }

电流:

enter image description here

在:
enter image description here

1 个答案:

答案 0 :(得分:7)

非常简单,您只需在每个按钮之间添加一个灵活的条形按钮项。请参阅以下内容:

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