I have a UICollectionView
in a UITableViewCell
. So the hierarchy is like this:
UITableView -> UITableViewCell -> UICollectionView - > UICollectionViewCell
What I want to achieve here is disable scrolling in UICollectionView
, and make it look like a big list of items. All content are created dynamically. So how do I resize an UICollectionView
depending on its cells. Its height should be equal to total of all UICollectionViewCells
.
Thanks!
Edit: I managed to disable scrolling and it worked. Then tried to resize the cell but it doesen't seem to do anything:
cell.viewscollectionview.scrollEnabled = false
cell.viewscollectionview.frame = CGRectMake(0, 0, tableView.frame.width, 800)
You must calculate UICollectionView height inside heightForRowAt
in tableView delegate.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// constants, should be initialized somewhere else
let totalItem: CGFloat = 20
let totalCellInARow: CGFloat = 3
let cellHeight: CGFloat = 120
let collViewTopOffset: CGFloat = 10
let collViewBottomOffset: CGFloat = 10
let minLineSpacing: CGFloat = 5
// calculations
let totalRow = ceil(totalItem / totalCellInARow)
let totalTopBottomOffset = collViewTopOffset + collViewBottomOffset
let totalSpacing = CGFloat(totalRow - 1) * minLineSpacing // total line space in UICollectionView is (totalRow - 1)
let totalHeight = (itemHeight * totalRow) + totalTopBottomOffset + totalSpacing
return totalHeight
}
For full tutorial, you can read it here: https://medium.com/@adinugroho/fixed-height-uicollectionview-inside-uitableview-79f24657d08f
Try using autolayouts. Use the collection view height constraint.Keep it constant in the beginning.Later as you add data to the cell adjust the height of collection view by changing the constant of the height constraint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With