Dynamic Height for a Uitableview Based on a Dynamic Collection View

Non-Scrolling UICollectionView inside UITableViewCell Dynamic Height

You need to bind your collectionView delegate/datasource with TableViewCell and need to use below func in tableViewcell. Make sure to turn off the CollectionView Scrolling.

override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

self.layoutIfNeeded()
let contentSize = self.cvSubcategory.collectionViewLayout.collectionViewContentSize
if self.cvSubcategory.numberOfItems(inSection: 0) < 4 {
return CGSize(width: contentSize.width, height: 120) // Static height if colview is not fitted properly.
}

return CGSize(width: contentSize.width, height: contentSize.height + 20) // 20 is the margin of the collectinview with top and bottom
}

Your project sample solution : https://github.com/thedahiyaboy/DynamicCollectionApp


For future purpose you can take ref from this post : Dynamic CollectionViewCell In TableViewCell Swift

How to use dynamic height of UITableViewCell in auto-layout and move other views to up when bottom view is hidden?

At first, make the height of UITableViewCell to UITableView.automaticDimension

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}

Embed all of your questionLabels in a UIStackView (vertical) excluding bottomLabel. Set AutoLayoutConstraint between UIStackView and bottomLabel.

Sample Image

Set the numberOfLines property of UILabels to 0(zero).

Sample Image

Set the Distribution of the UIStackView as Fill

Sample Image

Then, in your tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell method hide the labels. And it will automatically handle the spaces between UILabels

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell

cell.questionLabel1.text = labelOneText[indexPath.row]
cell.questionLabel2.text = labelTwoText[indexPath.row]
cell.questionLabel3.text = labelThreeText[indexPath.row]

if labelOneText[indexPath.row] == "" {
cell.questionLabel1.isHidden = true
}

if labelTwoText[indexPath.row] == "" {
cell.questionLabel2.isHidden = true
}

if labelThreeText[indexPath.row] == "" {
cell.questionLabel3.isHidden = true
}

return cell
}

Final Output:

Sample Image



Related Topics



Leave a reply



Submit