【问题标题】:UICollectionView Layout Wrong Item SizeUICollectionView 布局错误的项目大小
【发布时间】:2021-12-12 06:31:27
【问题描述】:

我正在以编程方式创建UICollectionViewController

class MyCollectionVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {


init() {
        super.init(collectionViewLayout: UICollectionViewFlowLayout())    
}


override func loadView() {
    super.loadView()

    self.collectionView.delegate = self

    ...
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
    UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let dimension = self.view.bounds/3
    return CGSize(width: dimension, height: dimension)

}

override final func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

 print ("Cell Size: (self.collectionViewLayout as! UICollectionViewFlowLayout).itemSize)

}

}

我实际上需要cellForItemAt 的单元格大小来做更多的工作。

上面的单元格大小始终打印为 50 x 50。这是给定的默认大小。 iPhone 或 iPad,横向纵向,总是 50。

奇怪的是,实际的单元格布局会正确显示。其他一切正常,看起来很完美。

我在这里错过了什么?

【问题讨论】:

  • 定义“更多工作”。不应该在单元格内完成更多的工作,这可能会根据其大小而不是根据collectionView(_:cellForItem:) 中的当前大小来改变它的 alyout?只需检查,在之前/之后调用哪个:sizeForItemAtcellForItemAtcellForItemAt 不应该只处理一些“逻辑”,但不需要所有 UI 吗?

标签: ios swift uicollectionview uicollectionviewlayout uicollectionviewflowlayout


【解决方案1】:

试试这个

class GridLayout: UICollectionViewFlowLayout {
    override init() {
        super.init()
        self.minimumLineSpacing = 0
        self.minimumInteritemSpacing = 0
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func prepare() {
        super.prepare()
        guard let collectionView = self.collectionView else {return}
        let cellWidth = collectionView.frame.width / 3
        self.itemSize = CGSize(width: cellWidth, height: cellWidth) // Your Cell Size
    }
}
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView.collectionViewLayout = GridLayout()
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
 
        print((self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize)
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Your Cell Id", for: indexPath)
        return cell
    }

【讨论】:

    猜你喜欢
    • 2020-04-06
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多