【问题标题】:How to make UICollectionView dynamic height?如何使 UICollectionView 动态高度?
【发布时间】:2021-10-23 03:22:49
【问题描述】:

如何让 UICollectionView 动态高度? UICollectionView 的高度应该取决于其中的单元格数量。

class ProduitViewController: UIViewController {
    
    var productCollectionViewManager: ProductCollectionViewManager?
    var sizeCollectionViewManager: SizeCollectionViewManager?
    var product: ProductModel?
    var selectedSize: String?
    
    @IBOutlet weak var productCollectionView: UICollectionView!
    @IBOutlet weak var sizeCollectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setup()
    }

}

private extension ProduitViewController {

    func setup() {
        
        guard let product = product else { return }
        colorNameLabel.text = product.color[0].name
        
        sizeCollectionViewManager = SizeCollectionViewManager.init()
        sizeCollectionView.delegate = sizeCollectionViewManager
        sizeCollectionView.dataSource = sizeCollectionViewManager
        sizeCollectionViewManager?.set(product: product)
        sizeCollectionViewManager?.didSelect = { selectedSize in
            self.selectedSize = selectedSize
        }
        sizeCollectionView.reloadData()
    }
}

集合视图管理器

import UIKit

final class SizeCollectionViewManager: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    var sizeProduct: [SizeModel] = []
    
    var didSelect: ((String) -> Void)?
    
    func set(product: ProductModel) {
        sizeProduct = product.size
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return sizeProduct.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SizeCell", for: indexPath) as? SizeCollectionViewCell {
            
            cell.configureCell(cellModel: sizeProduct[indexPath.row])
            return cell
        }
        
        return UICollectionViewCell.init()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let width = collectionView.frame.width / 3 + 20
        let height: CGFloat = 35
        
        return CGSize(width: width, height: height)
    }
}

现在高度为 35。如果不设置为静态,则集合视图将完全从屏幕上消失。

截图故事板

【问题讨论】:

    标签: ios swift xcode uicollectionview


    【解决方案1】:

    您应该在 UICollectionView 引用上设置高度限制。设置约束后,您可以根据对象的数量计算和设置约束值,因为您知道它应该显示多少行。

    【讨论】:

    • 我不知道它应该显示多少行。总是不同数量的单元格。
    猜你喜欢
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多