Beginning Auto Layout - Part 3: Stack Views | Ray Wenderlich

Stack Views are powerful layout tools that let you create simple to extremely complex layouts, in a minimum of time.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3937-beginning-auto-layout/lessons/3

Hi,
I am having an issue in using UIStackView with collection view and a button. Can you please assist me in solving this.

I

I want my views to be arranged like the above image. When I tried with UIStackView its not properly aligning. Here is my code.

    let actionsStack = UIStackView(arrangedSubviews: [reactionsCollectionView, replyActionButton])
    actionsStack.translatesAutoresizingMaskIntoConstraints = false
    actionsStack.axis = .horizontal
    actionsStack.alignment = .center
    actionsStack.distribution = .fill
    actionsStack.spacing = 8.0
    
    actionButtonContainer.addSubview(actionsStack)
    actionsStack.fillSuperview()
    
    addSubview(actionButtonContainer)
    
    replyActionButton.rightAnchor.constraint(equalTo: actionsStack.rightAnchor, constant: 0.0).isActive = true
    replyActionButton.widthAnchor.constraint(equalToConstant: 22).isActive = true
    replyActionButton.heightAnchor.constraint(equalToConstant: 22).isActive = true         
    
    reactionsCollectionView.setContentHuggingPriority(249, for: .horizontal)
    reactionsCollectionView.setContentCompressionResistancePriority(749, for: .horizontal)

When I set .aligment = .center. I am not able to see my collectionview. Am I doing anything something wrong?. Please assist me.

Attached is the result I am getting.

First, the intrinsic size of the button should probably set its size, rather than explicit height and width. What is setting the size of the collection view? Do you have an explicit size for the cells or auto sizing? When you break in the debugger, what does the view hierarchy look like?

Jerbeers,

The CollectionView which you are seeing is a nested horizontal collectionview inside the main collectionview cell. The container which is holding these controls has a fixed height of 30 pts. Inside this container, I want to use stackview to align these controls.

I am attaching the sample design of it. You will have a better idea.

Do you need a collection view for the inner controls? Will it scroll horizontally? If not, an embedded stack view might be simpler. In any case, the key to debugging issues like these is to break in the debugger and look at the visual debug hierarchy. That will show you what views are being laid out and where. Then you have to drill down to figure out why and what to change.