Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIStackView - Want a percentage to define each item

I want to put two views into a UIStackView. I want the top item to always be 30% of the space no matter what device (or orientation) that it appears. Thus, I want to have the bottom view to be 70%. How do I tell a UIStackView that I want to use a percentage?

Example resulting view

like image 402
user3615480 Avatar asked Apr 27 '16 11:04

user3615480


3 Answers

Just set a constraint for the top view.

In the storyboard's Document Outline control-drag from the top view to the stack view and select Equal heights. This will make their heights equal. Now go to the Size Inspector and you should see the constraint. Double click on it and set the multiplier to 0.3. Then update the frames.

If the bottom view doesn't automatically size or it gives you an error telling that you need a height constraint, just repeat the process, but now set the multiplier to 0.7.

like image 103
Lawrence413 Avatar answered Oct 17 '22 08:10

Lawrence413


From apple documentation

UIStackViewDistributionFillProportionally A layout where the stack view resizes its arranged views so that they fill the available space along the stack view’s axis. Views are resized proportionally based on their intrinsic content size along the stack view’s axis.

So according to this you should set UIStackView distribution property to UIStackViewDistributionFillProportionally and set intrinsic size, its.

You can get more info here and on Intrinsic content size

like image 29
Adnan Aftab Avatar answered Oct 17 '22 07:10

Adnan Aftab


Swift 5.2

To implement this programmatically

Setting UIView to always be 30% of the size of it's superview within a UIStackView

viewA.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3).isActive = true

Full code implementation:

// Configure the StackView
let stackView = UIStackView()

stackView.axis = .vertical
stackView.distribution = .fill
view.addSubview(stackView)

stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

// Configure View A
let viewA = UIView()
viewA.backgroundColor = .darkGray
viewA.translatesAutoresizingMaskIntoConstraints = false

// Configure View B
let viewB = UIView()
viewB.backgroundColor = .lightGray
viewB.translatesAutoresizingMaskIntoConstraints = false

// Add Views to StackView
stackView.addArrangedSubview(viewA)
stackView.addArrangedSubview(viewB)

// Set the height percentage multiplier to View A
viewA.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3).isActive = true
like image 3
rbaldwin Avatar answered Oct 17 '22 09:10

rbaldwin