Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIStackView proportional layout with only intrinsicContentSize

I'm experiencing problems with layout of arranged subviews in UIStackView and was wondering if someone could help me understand what's going on.

So I have UIStackView with some spacing (for example 1, but this does not matter) and .fillProportionally distribution. I'm adding arranged subviews with only intrinsicContentSize of 1x1 (could be anything, just square views) and I need them to be stretched proportionally within stackView.

The problem is that if I add views without actual frame, only with intrinsic sizes, then I get this wrong layout

wrong layout

Otherwise, if I add views with frames of the same size, everything works as expected,

correct layout

but I really prefer not to set view's frame at all.

I'm pretty sure that this is all about hugging and compression resistance priority, but can't figure out what right answer is.

Here is an Playground example:

import UIKit
import PlaygroundSupport

class LView: UIView {

    // If comment this and leave only intrinsicContentSize - result is wrong
    convenience init() {
        self.init(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
    }

    // If comment this and leave only convenience init(), then everything works as expected
    public override var intrinsicContentSize: CGSize {
        return CGSize(width: 1, height: 1)
    }
}

let container = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
container.backgroundColor = UIColor.white

let sv = UIStackView()
container.addSubview(sv)


sv.leftAnchor.constraint(equalTo: container.leftAnchor).isActive = true
sv.rightAnchor.constraint(equalTo: container.rightAnchor).isActive = true
sv.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
sv.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
sv.translatesAutoresizingMaskIntoConstraints = false
sv.spacing = 1
sv.distribution = .fillProportionally

// Adding arranged subviews to stackView, 24 elements with intrinsic size 1x1
for i in 0..<24 {
    let a = LView()
    a.backgroundColor = (i%2 == 0 ? UIColor.red : UIColor.blue)
    sv.addArrangedSubview(a)
}
sv.layoutIfNeeded()

PlaygroundPage.current.liveView = container
like image 576
Arthur Grishin Avatar asked Sep 16 '17 11:09

Arthur Grishin


People also ask

What is fill proportionally in Uistackview?

case fillProportionally. 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.

What is Intrinsiccontentsize?

Intrinsic content size is information that a view has about how big it should be based on what it displays. For example, a label's intrinsic content size is based on how much text it is displaying. In your case, the image view's intrinsic content size is the size of the image that you selected.

What is Uistackview?

A streamlined interface for laying out a collection of views in either a column or a row.


1 Answers

This is obviously a bug in the implementation of UIStackView (i.e. a system bug).

DonMag already gave a hint pointing in the right direction in his comment:

When you set the stack view's spacing to 0, everything works as expected. But when you set it to any other value, the layout breaks.


Here's the explanation why:

ℹ️ For the sake of simplicity I will assume that the stack view has

  • a horizontal axis and
  • 10 arranged subviews

With the .fillProportionally distribution UIStackView creates system-constraints as follows:

  • For each arranged subview, it adds an equal width constraint (UISV-fill-proportionally) that relates to the stack view itself with a multiplier:

    arrangedSubview[i].width = multiplier[i] * stackView.width
    

    If you have n arranged subviews in the stack view, you get n of these constraints. Let's call them proportionalConstraint[i] (where i denotes the position of the respective view in the arrangedSubviews array).

  • These constraints are not required (i.e. their priority is not 1000). Instead, the constraint for the first element in the arrangedSubviews array is assigned a priority of 999, the second is assigned a priority of 998 etc.:

    proportionalConstraint[0].priority = 999 
    proportionalConstraint[1].priority = 998 
    proportionalConstraint[2].priority = 997 
    proportionalConstraint[3].priority = 996
    ...         
    proportionalConstraint[n–1].priority = 1000 – n
    

    This means that required constraints will always win over these proportional constraints!

  • For connecting the arranged subviews (possibly with a spacing) the system also creates n–1 constraints called UISV-spacing:

    arrangedSubview[i].trailing + spacing = arrangedSubview[i+1].leading
    

    These constraints are required (i.e. priority = 1000).

  • (The system will also create some other constraints (e.g. for the vertical axis and for pinning the first and last arranged subview to the edge of the stack view) but I won't go into detail here because they're not relevant for understanding what's going wrong.)

Apple's documentation on the .fillProportionally distribution states:

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 the multiplier for the proportionalConstraints should be computed as follows for spacing = 0:

  • totalIntrinsicWidth = ∑iintrinsicWidth[i]
  • multiplier[i] = intrinsicWidth[i] / totalIntrinsicWidth

If our 10 arranged subviews all have the same intrinsic width, this works as expected:

multiplier[i] = 0.1

for all proportionalConstraints. However, as soon as we change the spacing to a non-zero value, the calculation of the multiplier becomes a lot more complex because the widths of the spacings have to be taken into account. I've done the maths and the formula for multiplier[i] is:

How the stack view should compute the multiplier


Example:

For a stack view configured as follows:

  • stackView.width = 400
  • stackView.spacing = 2

the above equation would yield:

multiplier[i] = 0.0955

You can prove this correct by adding it up:

(10 * width) + (9 * spacing)
    = (10 * multiplier * stackViewWidth) + (9 * spacing)
    = (10 * 0.0955 * 400) + (9 * 2)
    = (0.955 * 400) + 18
    = 382 + 18
    = 400
    = stackViewWidth

However, the system assigns a different value:

multiplier[i] = 0.0917431

which adds up to a total width of

(10 * width) + (9 * spacing)
    = (10 * 0.0917431 * 400) + (9 * 2)
    = 384,97
    < stackViewWidth

Obviously, this value is wrong.

As a consequence the system has to break a constraint. And of course, it breaks the constraint with the lowest priority which is the proportionalConstraint of the last arranged subview item.

That's the reason why the last arranged subview in your screenshot is stretched.

If you try out different spacings and stack view widths you'll end up with all sorts of weird-looking layouts. But they all have one thing in common: The spacings always take precedence. (If you set the spacing to a greater value like 30 or 40 you'll only see the first two or three arranged subviews because the rest of the space is fully occupied by the required spacings.)


To sum things up:

The .fillProportionally distribution only works properly with spacing = 0.

For other spacings the system creates constraints with an incorrect multiplier.

This breaks the layout as

  • either one of the arranged subviews (the last) has to be stretched if the multiplier is smaller than it should be
  • multiple arranged subviews have to be compressed if the multiplier is greater than it should be.

The only way out of this is to "misuse" plain UIViews with a required fixed-width constraint as spacings between the views. (Normally, UILayoutGuides were introduced for this purpose but you cannot even use those either because you cannot add layout guides to a stack view.)

I'm afraid that due to this bug, there is no clean solution to do this.

like image 59
Mischa Avatar answered Sep 29 '22 10:09

Mischa