UICollectionViewCell content wrong size on first load

前端 未结 5 1709
感情败类
感情败类 2020-12-15 02:52

I have a added a UICollectionView to my UIViewController and have made a custom cell for it.

I set the size of the cell using the siz

相关标签:
5条回答
  • 2020-12-15 03:23

    Thanks to the great tip by vin047.

    In our case I found that the super-call-order issue was the problem.

    But with the overall table view (or collection view). Not in the cell as such.

    Works:

    class UnusualCollectionView: UICollectionView {
        override func layoutSubviews() {
            super.layoutSubviews()
            contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
        }
    

    Fails very erratically, particularly on first appearance:

    class UnusualCollectionView: UICollectionView {
        override func layoutSubviews() {
            contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
            super.layoutSubviews()
        }
    

    The problem caused some profoundly erratic behavior. For example, the 12th cell (no really) was always displaced a long way vertically. Always the 12th cell! Who knows?

    vin047 saved the day here, bravo.

    0 讨论(0)
  • 2020-12-15 03:25

    It looks like it still retains it's 100x100px basic size for the contentView while the cell itself gets the right size already. You can force the layout to reset adding the following line just before you return the cell:

    cell?.layoutIfNeeded()
    
    0 讨论(0)
  • 2020-12-15 03:27

    What worked for me was changing Estimate Size on the Collection View from Automatic to None.

    0 讨论(0)
  • 2020-12-15 03:28

    I had once similar problem (content of my cell was not fitting cell even with correct autolayout). The bug was caused by not calling super.layoutSubviews() in overriden function layoutSubviews() that was in Cell's class.

    0 讨论(0)
  • 2020-12-15 03:43

    For those using Storyboard + AutoLayout, and choosing which constraints are active at runtime:

    When using dequeueReusableCell, on first load, the cell is created but its view has not been initialised, so the constraint changes aren't saved - whatever you have set in Storyboard is used. Solution for me was to update the constraints after the view has loaded:

    override func layoutSubviews() {
        super.layoutSubviews()
        adjustIconWidths()
    }
    
    0 讨论(0)
提交回复
热议问题