Nested vertical UICollectionView and dynamic height - swift

I have a parent UICollectionView that nests 2 other UICollectionViews:
Parent UICollectionView (Vertical)
First nested UICollectionView (Horizontal) - Grey
Second nested UICollectionView (Vertical) - Red
The parent UICollectionView
I use numberOfSections(in collectionView:) and manually set the number of sections in the parent collection view. In this case I return 2; one for first (grey) nested horizontal UICollectionView and one for the second (red) nested vertical UICollectionView
Then in collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) I return 1. That means each nested UICollectionView will be placed inside a single item.
For each section I dequeue collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) a specific cell [see Nested UICollectionViews step 3] for the first nested horizontal UICollectionView and a specific cell [see Nested UICollectionViews step 3] for the second nested vertical UICollectionView.
Then I set the size of each item in section using collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath). This is where my problem begins. But let me continue on how I setup the nested UICollectionViews.
Nested UICollectionViews
This is a 3-step procedure for each nested UICollectionView:
I create the UICollectionViewCell (the appearance of the cell)
I use a UICollectionViewController to:
Fetch the data from Firebase
Dequeue the cell mentioned in step 1 and pass in the data fetched from Firebase
Set the dimensions of each item using collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath)
I create another UICollectionViewCell that:
Initializes the UICollectionViewController mentioned in step 2
Uses the view of this UICollectionViewController and adds it to the cell's contentView by filling the superview (aka the cell)
contentView.addSubview(UICollectionViewController().view) UICollectionViewController().view.fillSuperview()
The problem
When I set the dimensions of the section where the horizontal UICollectionView (grey) will be, I just need to match the height of the UICollectionView to the height of each cell.
But when I set the dimensions of the section where the vertical UICollectionView will be (red) I need to know the number of cells to calculate the correct height. Otherwise, the section could either be too big or too small.
Any idea how I can notify the parent UICollectionView controller of the number of cells of the vertical nested collection view?
Thanks in advance.

For those nested behaviours I recommend creating UICollectionView by code, instead of IB Storyboard, so you do not have to deal so much with autoresizing constraints. You can create UICollectionView programmatically (instead of UICollectionViewController with desired frame.size and then assigning UICollectionViewFlowLayout to it so you can better controll how big should be your item layout in your nested collectionView based on its frame. Some example code is here:
lazy var layout: UICollectionViewFlowLayout = {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.itemSize = self.frame.size
layout.scrollDirection = .horizontal
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
return layout
}()
lazy var customCollectionView: UICollectionView = {
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width * 0.5), collectionViewLayout: self.layout)
collectionView.backgroundColor = UIColor.clear
collectionView.dataSource = self
collectionView.delegate = self
let collectionCellNib = UINib.init(nibName: "CustomCell", bundle: Bundle.main)
collectionView.register(collectionCellNib, forCellWithReuseIdentifier: "customCellId")
return collectionView
}()

Related

Auto-Layout for CollectionViewCell: Trailing/Leading constraints change cell size

I just can´t get familar with auto layout in Xcode. When I set trailing and leading constrains for Header Stack View, Bottom Stack View or the image between them, then the size (height/width) of my cell changes. Why does it happen and how can I avoid it? I think something isn´t right with the kind I build layouts. I am very grateful for any help.
I set the cell size with this code:
extension MainVC: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = view.frame.size.height
let width = view.frame.size.width
return CGSize(width: width * 0.42, height: height * 0.3)
}
}
My cell layout:
This is how the app looks when I use constrains for the Bottom Stack View.
This is without constrains for the Bottom Stack View (correct cell size).
Cells can now self-size with auto layout and ignore what you return in collectionView(_:layout:sizeForItemAt:). If you want to use collectionView(_:layout:sizeForItemAt:), change Estimate size to None in the storyboard.
https://stackoverflow.com/a/58369142/14351818

Vertical and Horizontal Scrolling When Embedding a Table View in a Collection View that has a Collection View Header and Horizontal Flow Layout

I am trying to implement an application that allows a user to swipe horizontally between collection view cells while also being able to scroll vertically to see the entire content of a particular cell.
I want all the collection view cells to have a table view embedded within them.
The problem I am running into as of now is that my horizontal scrolling works as I have set the collection view flow layout to horizontal. I know that collection view flow layouts can only support one direction. Because of this, I tried to implement the following solution.
As of now within my project, I have a view controller with a scroll view inside. Embedded within the scroll view, is a collection view. This collection view has its own header implemented via dequeueReusableSupplementaryView.
I know that constraints can often be an issue preventing vertical scrolling to take place so here is a picture of my constraints:
Additionally, here is some code that I have used to implement this system:
Determining the scroll view content size
override func viewDidLayoutSubviews() {
super.viewWillLayoutSubviews()
scrollView.contentSize.height = collectionView.frame.size.height
scrollView.contentSize.width = self.view.frame.size.width
}
Setting up the collection view
func setupCollectionView() {
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "TableViewHolderCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "tableViewHolderCollectionViewCell")
collectionView.register(UINib(nibName: "CustomCollectionViewHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "CustomCollectionViewHeaderView")
collectionView.delaysContentTouches = true
collectionView.contentInsetAdjustmentBehavior = .never
collectionView.bounces = false
collectionView.isPagingEnabled = true
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
layout.sectionHeadersPinToVisibleBounds = true
layout.sectionInset = UIEdgeInsets(top: 0, left: -self.view.frame.size.width, bottom: 0, right: 0)
collectionView.setCollectionViewLayout(layout, animated: false)
}
Setting up the collection view data
extension TasksAndScheduleViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "tableViewHolderCollectionViewCell", for: indexPath) as! TableViewHolderCollectionViewCell
cell.backgroundColor = colorArray[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 343)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//setting up header view
return headerView
}
}
After trying to debug, I realized that the collection view vertical scroll might have been overriding the vertical scroll of the scroll view I had added to my view controller. In order to solve this, I created a custom class (as seen below) which my collection view implemented. To my knowledge, this was successful at disabling the vertical scroll for the collection view but it was not successful in enabling the other scroll view's vertical scroll.
class CollectionViewVerticalScroll: UICollectionView {
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
let direction = panGestureRecognizer.direction(in: self)
if direction.contains(.Down) || direction.contains(.Up) {
return false
}
return true
}
}
My desired goal is to have the ability to swipe horizontally between these collection view cells that have table views while also being able to vertically scroll the collection view cell and the contents of the table view embedded inside of it. Ideally, the vertical scroll should allow me to scroll the table view cells while also moving the entire view upwards. The closest example to what I am trying to implement that I could find online is twitter's search page. The only difference is that my application has a collection header view and no navigation bar. I have attached a picture below:
I would appreciate any help. Please do let me know if you have any questions or if something doesn't make sense to you.

Collection cell wrongly resized in reloadData

I don't know why but the cells of my collectionView are automatically wrongly resized after a reloadData.
After first init, then after reloadData :
I'm using UICollectionViewDelegateFlowLayout to define the size of the cell but it don't take care of it :
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let paddingSpace = sectionInsets.left * (2 + 1)
let availableWidth = view.frame.width - paddingSpace
let widthPerItem = availableWidth / 2
return CGSize(width: widthPerItem, height: widthPerItem)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInsets.left
}
When execution come in the cellForItemAt, the cell have the right size, the shadow is created in this function and it have the right width.
One last thing is that only the width is resized, the height stay as I want.
Does any one have an idea why the width is resized wrongly after the reloadData ?
I was having a similar issue when making an extension of the UICollectionViewDelegateFlowLayout and it turns out that setting the collectionView's Estimated Size to "None" in the storyboard (Size Inspector) solved it.
As stated in the Xcode 11 Release Notes:
Cells in a UICollectionView can now self size with Auto Layout
constrained views in the canvas. To opt into the behavior for existing
collection views, enable “Automatic” for the collection view’s
estimated size, and “Automatic” for cell’s size from the Size
inspector.
If deploying before iOS 13, you can activate self sizing collection
view cells by calling performBatchUpdates(_:completion:) during
viewDidLoad(). (45617083)
So, newly created collectionViews have the attribute "Estimated Size" set as "Automatic" and the cell's size is computed considering its subview dimensions, thus ignoring the UICollectionViewDelegateFlowLayout extension methods, even though they are called.

Setting CollectionView cell height to dynamic based on content

I have an application where I am using collectionview to display content which includes imageview, about 4 uilabels and a stackview which are all constrained to each other. This cell is scrollable vertically and not horizontally as I have to make provison for larger screen size like the iPad. The problem I have now is my CollectionViewFlowLayout height is static, How can I make it dynamic so that it resizes base on the height of the retuned content. the text of the label could vary so how do I handle this
below is how I have made my cell
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.size.width, height: 400)
}
further code would be added on request and any help is appritiated

How to make 2 rows in horizontal collection view without using sections

The horizontal scrolling in UICollectionView only returns one row and I need to make a horizontal scrolling collection view with 2 rows just like the image below
[1]: https://i.stack.imgur.com/Vs1kt.png :[1]
You need to set fix height of the CollectionView and then use sizeForItemAt() under UICollectionViewDelegateFlowLayout which returns CGSize. You have to manage the cell height something like this.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 50.0, height: collectionViewHeight / 2) //<-- Manage height and width accordingly.
}