0
votes

I am working in a mainStackView (UIStackView) that has 4 horizontal subviews (rows), and it works fine as follows (the mainStackView is managed with AutoLayout constraints):

    rowsArray = Array<UIView>()
    for _ in 0...3 {
        let row = UIView()
        row.backgroundColor = UIColor.randomColor() //color for debugging
        rowsArray.append(row)
    }

    mainStackView = UIStackView(arrangedSubviews: rowsArray)
    mainStackView.axis = .vertical
    mainStackView.alignment = .fill
    mainStackView.distribution = .fillEqually
    mainStackView.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(mainStackView)

Now, given that each subview (row in this case) will have a number of horizontal subviews in it, I need the arrangedSubviews to be Array, but it fails to display any of the subviews.

    rowsArray = Array<UIStackView>()
    for _ in 0...3 {
        let row = UIStackView()
        row.backgroundColor = UIColor.randomColor() //color for debugging
        rowsArray.append(row)
    }

Any idea why the UIStackView does not behave as the superclass (UIView), or if there is any other consideration for nesting UIStackViews programmatically

Rgds... e

1

1 Answers

1
votes

That's not a bug, it is designed to be like that, read the following excerpt of the docs, section Managing the Stack View’s Appearance:

The UIStackView is a nonrendering subclass of UIView; that is, it does not provide any user interface of its own. Instead, it just manages the position and size of its arranged views. As a result, some properties (like backgroundColor) have no effect on the stack view.

That means that UIStackView is not a classic UIView, but rather a nice interface for layout out its subviews. There is no sense in creating a UIStackView that has no arranged subviews (which is your case).

Add subviews to those rows you create, set their background color to red, and you'll see:

rowsArray = Array<UIStackView>()
for _ in 0...3 {
    let row = UIStackView()
    let view = UIView()
    view.backgroundColor = UIColor.randomColor() //color for debugging
    row.addArrangedSubview(view)
    rowsArray.append(row)
}

Regarding nested stackViews, I've been using it for a fair amount of time without a problem, so I believe it is a way to go.