pbm pbm - 1 year ago 138
iOS Question

In Xcode, set UIButtons the same width except if they truncate their text label

I'm using Xcode 8.1. I have a horizontal stackview that contains 3 buttons, spaced as shown in the picture (the ugly colours are just to make the buttons clear to see).

enter image description here

I'd like each button to be the same width unless the text of a button cannot fit. The next picture shows what happens on a smaller phone. Notice the word "RECOMMENDED" is truncated.

enter image description here

If the text cannot fit I'd like that button to expand its width until the text fits, with the other 2 buttons getting smaller but staying the same size as each other.

Through interface builder constraints and properties I have been unable to make this work. I've tried permutations of the content compression resistance priorities of buttons, setting all buttons "equal width", and the stack view distribution property. Setting equal width, for example, causes the content resistance priority to be ignored.

Ideally I'd like to make a rule such as "set each button the same width unless the text label will not fit, in which case let that button get bigger to fit the label". Can you suggest a way to accomplish this? I'm guessing this is beyond interface builder and will need to be implemented in code.

MORE INFO ABOUT THE ANSWER TO THIS QUESTION: asmi85 provided a correct solution to this question (thanks!). By decreasing the priority of the width constraints they become optional contraints, as described in section "Constraint Priorities" of the Apple Auto Layout Guide (https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/AnatomyofaConstraint.html#//apple_ref/doc/uid/TP40010853-CH9-SW1). Each UIButton has Content Compression Resistance Priority = 750.

When calculating solutions, Auto Layout attempts to satisfy all the constraints in priority order from highest to lowest. If it cannot satisfy an optional constraint, that constraint is skipped and it continues on to the next constraint.

When Auto Layout cannot fully display all button label and have all buttons the same width, it skips the width rules it cannot satisfy.

Answer Source

Create equal width constraint between first button and second button and set the priority to low(250), then between second and third button with priority to low and then between third and first and priority again to low.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download