1

Souce Code : My code

I need to create layout having dynamic size as per the text of different length, for that using collectionview inside tableview cell

I have created custom collectionview with self sizing collectionview cell in it. I have used CustomFlowLayout(sub class of UICollectionViewLayout) with prepare override method to calculate size of each cell.

I am able to achieve the dynamic size collectionview cell, now I need to make collectionview height dynamic based on its content size, as of now I have taken height contstraint of collectionview and set it as 200 fixed.

Need help regarding how to set collectionview height dynamically based on its content and at the same time adjust the parent tableview cell to fit the its content

Below is the screenshot of what I want to achieve, Thanks much!

DynamicContentSize

Dhaval H. Nena
  • 3,992
  • 1
  • 37
  • 50
  • If you are showing list, then why to use collection, use table. Or do you have any specific design challenge? Let us know. – Bista Jan 10 '19 at 07:23
  • Requirement is as such that we need to show list with dynamic size, if two small words are there then it should be placed side by side not up and down – Dhaval H. Nena Jan 10 '19 at 07:33
  • 1
    You need to use table view instead of collection view. – AtulParmar Jan 10 '19 at 07:48

3 Answers3

0

In your CustomFlowLayout which is subclass of UICollectionViewLayout you need to override the collectionViewContentSize as shown below.

Calculate your content height & return it.

override public var collectionViewContentSize: CGSize {
    return CGSize(width: collectionViewWidth, height: contentHeight)
}

Hope it helps!

0

Try adjusting your collection view height using

if heightConstraint.constant != collectionView.contentSize.height {
    heightConstraint.constant = collectionView.contentSize.height
    view.updateConstraintsIfNeeded()
}

And you can set your tableview row height as automatic. if your contraints are proper the tableview cell will automatically adjust its height

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}
Shruti
  • 1,849
  • 1
  • 13
  • 21
0

I have already answered this question here: https://stackoverflow.com/a/53102033/7388630

You can get fully working and explained code sample here

fewlinesofcode
  • 3,007
  • 1
  • 13
  • 30
  • Link for your fully working code sample is not working, can you please share the working one? Thanks – Dhaval H. Nena Jan 11 '19 at 09:45
  • That’s actually weird. It works for me. https://fewlinesofcode.com/swift,/uicollectionview/2018/11/01/uicollectionview-dynamic-cell-height.html – fewlinesofcode Jan 11 '19 at 09:48
  • Thanks for the new link, I was able to download your code, it seems your collection view is not resizing based on its cell size, your cell is resizing based on their content in your code label. – Dhaval H. Nena Jan 16 '19 at 11:37