What's needed to stack multiple UICollectionView's vertically on the same UIViewController? I have added my code below and the issue that I am having is I do not see the StoryCollectionView. When I check out the View Hierarchy I see that PostCollectionView takes up the entire screen from top to bottom and I also see that StoryCollectionView is underneath on its own view also taking up the entire screen. What I'm trying to achieve is having StoryCollectionView at the top of the screen and PostCollectionView (vertically scrollable) right beneath it
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: view.frame.width, height: ((view.frame.width * 0.75) + (view.frame.width / 3 - 8.75) * 0.75) - 38)
storyCollectionView = StoryCollectionView(frame: view.frame, collectionViewLayout: layout)
view.addSubview(storyCollectionView)
NSLayoutConstraint.activate([
storyCollectionView.topAnchor.constraint(equalTo: view.topAnchor)
])
postCollectionView = PostCollectionView(frame: view.frame, collectionViewLayout: layout)
view.addSubview(postCollectionView)
NSLayoutConstraint.activate([
postCollectionView.topAnchor.constraint(equalTo: storyCollectionView.bottomAnchor)
])
The problem is that your constraints aren't setup correctly. In your case, you need to define the height of each collection view, as well as a top, leading, and trailing anchor constraint. Here's how you would stack two collection views with a height of 250:
NSLayoutConstraint.activate([
storyCollectionView.topAnchor.constraint(equalTo: view.topAnchor),
storyCollectionView.heightAnchor.constraint(equalToConstant: 250),
storyCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
storyCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
NSLayoutConstraint.activate([
postCollectionView.topAnchor.constraint(equalTo: storyCollectionView.bottomAnchor),
postCollectionView.heightAnchor.constraint(equalToConstant: 250),
postCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
postCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
Also make sure you set the translatesAutoresizingMaskIntoConstraints
property to false
on both collection views.