简体   繁体   中英

CollectionView with height equal to max height of CustomCell in Swift

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)

collectionView(_:layout:sizeForItemAt:)方法中,在此处返回最大高度。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM