1

In a vertical UIStackView I have stacked four UIButtons. The UIStackView is centered (vertically and horizontally), the left side corresponds to the left edge of the device and the right side to the right. Inside the stackview, the buttons take all the horizontal space the stackview takes, so the stackview and its content share their width.

Now, I want to reduce the width of my buttons, so that they are 80% the width of the container (on any device except for iPad) and I want to center them too.

How can I do? I need a solution either in code (Swift) and using any possible property I can't find in XCode

2 Answers2

0

Instead of pinning the stack view to both sides of its superview, give it a width constraint that causes it to be 80% of the width of its superview.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Hi matt, thanks, this is the solution I had in mind but I thought it was possible something different. I love your books. :-) –  Mar 22 '16 at 07:11
  • 1
    Thanks! :) See also this question and answer on how to use the `multiplier` of a constraint to specify a percentage of the total: http://stackoverflow.com/questions/26373598/how-to-create-percentage-of-total-width-using-autolayout/26373646#26373646 – matt Mar 22 '16 at 14:24
0

The best working solution is button.widthAnchor.constraint(equalToConstant:self.stackview.frame-30).isActive = true

This works perfectly fine.

  • Thanks (nowadays I'm not even doing any mobile development anymore!) –  Dec 01 '18 at 18:43