Created
July 11, 2018 12:42
-
-
Save boazFrenkel/35b875f5d026e96981225dfcc9ad0623 to your computer and use it in GitHub Desktop.
example UICollectionView with dynamic height inside a UITableViewCell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************** | |
My cell has a label and under it a collection view with varying number of buttons in different sizes | |
So I'm letting Autolayout set the position of things and then taking all heights together for the cell height size | |
*************/ | |
class ButtonCollectionCell: UITableViewCell { | |
@IBOutlet weak var titleLabel: UILabel! | |
@IBOutlet weak var collectionViewDistanceFromCellBottomConstraint: NSLayoutConstraint! | |
@IBOutlet weak var distanceBetweenCollectionToLabelConstraint: NSLayoutConstraint! | |
@IBOutlet weak var buttonsCollectionView: UICollectionView! | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
let layout = CenterAlignedCollectionViewFlowLayout() | |
layout.scrollDirection = .vertical | |
layout.minimumLineSpacing = 5 | |
layout.minimumInteritemSpacing = 5 | |
layout.estimatedItemSize = CGSize(width: 1, height: 1) | |
buttonsCollectionView.register(MDCChipCollectionViewCell.self, forCellWithReuseIdentifier: "MDCChipCollectionViewCell") | |
buttonsCollectionView.setCollectionViewLayout(layout, animated: false) | |
buttonsCollectionView.allowsMultipleSelection = true | |
buttonsCollectionView.isScrollEnabled = true | |
} | |
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize { | |
//Comment: here we give the collectionView to layout it's items with a very large height so it will take all the space he needs and then we calculate the cell height with all the constraints in place (this method is called after the storyboard constraints are set so you have to take them into account | |
//Maybe it clearer to write all these outlets by code and keep constants for the constraints and not use constraint outlets | |
buttonsCollectionView.frame = CGRect(x: buttonsCollectionView.frame.origin.x, y: buttonsCollectionView.frame.origin.y, width: buttonsCollectionView.frame.width , height: 10000) | |
buttonsCollectionView.layoutIfNeeded() | |
let newCellSize = CGSize(width: buttonsCollectionView.collectionViewLayout.collectionViewContentSize.width, height: buttonsCollectionView.collectionViewLayout.collectionViewContentSize.height + collectionViewDistanceFromCellBottomConstraint.constant + distanceBetweenCollectionToLabelConstraint.constant + titleLabel.frame.height) | |
return newCellSize | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment