Reputation: 495
I am trying to have collection view(horizontal/vertical) with some height. Inside this, I have custom cells with many subviews(ex:image, title, description, last updated etc. ).
Now I want all cells to maintain same height which is the max height of all cells(based on data). (Each Cell height = Cell with max height)
I am able to create dynamic height cell but could not understand where to put the max height logic.
Currently I have following code
ViewController
lazy var flowLayout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal // .vertical
layout.minimumInteritemSpacing = 10
return layout
}()
lazy var collectionView: UICollectionView = {
let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
cv.backgroundColor = .white
return cv
}()
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let targetWidth = collectionView.bounds
.inset(collectionView.contentInset)
.inset(flowLayout.sectionInset)
.width
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! SampleCell
cell.configure(data: randomTexts[indexPath.row])
let size = cell.systemLayoutSizeFitting(
.init(width: targetWidth, height: 0),
withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
return size
}
SampleCell : UICollectionViewCell
override func systemLayoutSizeFitting( _ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority,
verticalFittingPriority: UILayoutPriority) -> CGSize {
let contentSize = contentView.systemLayoutSizeFitting(
targetSize,
withHorizontalFittingPriority: horizontalFittingPriority,
verticalFittingPriority: verticalFittingPriority)
return contentSize.withWidth(targetSize.width)
}
Extensions
extension CGRect {
func inset(_ insets: UIEdgeInsets) -> CGRect {
return self.inset(by: insets)
}}
Where will max height logic goes: ViewController or SampleCell and how to achieve the same?
Note: Also looking on how to do this for horizontal/vertical scrolling( collection with some height(and adjust a/c to the cell content) inside a viewcontroller)
Upvotes: 3
Views: 2045
Reputation: 543
Inside the collectionView(_:layout:sizeForItemAt:)
method, return the max height here.
Upvotes: 1