Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable scrolling in UICollectionView and resize it to wrap all cells

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)
like image 580
Doge Dogeoglu Avatar asked Jan 15 '16 12:01

Doge Dogeoglu


2 Answers

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

like image 190
Adi Nugroho Avatar answered Sep 28 '22 05:09

Adi Nugroho


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.

like image 41
Vidya Avatar answered Sep 28 '22 07:09

Vidya