How to align UIBarButtonItem in UIToolbar in iOS universal app?

Blaszard picture Blaszard · Aug 15, 2014 · Viewed 33.6k times · Source

I want to put two UIBarButtonItem instances to UIToolbar in my iOS universal app, on which the first item is on the left-edge of the toolbar and the second is on the center. However, it looks like this cannot be done in Interface Builder, because the auto layout doesn't support forcing constraints on UIBarButtonItem class due to the fact that it is not a subclass from UIView.

Notice that I don't want to put the first on the left-edge and the second is on the right-edge - I have to put the second button at the center. Also, I don't have a plan to use the third button in order to align them as left, center, and right at equal interval.

Is it still possible to add such constraint in this situation in storyboard? I use Xcode 6 beta 5.

Answer

Imanou Petit picture Imanou Petit · Aug 15, 2014

You can do it all in your Storyboard.

Select a Bar Button Item in the Object library and drag it into your Toolbar. Add a Flexible Space Bar Button Item at its right. Add your second Bar Button Item at its right. Then, add a second Flexible Space Bar Button Item at its right.

The result will look like this in Interface Builder:

enter image description here

If necessary, you can add an extra Fixed Space Bar Button Item at the right edge of your Toolbar to be sure that your second Bar Button Item is really centered.

User lxt gives another example of this in answer for a similar question here.

Edit: Be sure that your UIToolbar has good constraints before proceeding!