为什么 invalidateLayout 不触发 UICollectionView 中的 sizeForItemAtIndexPath? (附代码)

why is invalidateLayout is not triggering sizeForItemAtIndexPath in UICollectionView? (code attached)

问题是 collection视图中的列数在旋转时不会保持在 7(所需数量)。需要更改什么代码才能解决此问题?

自定义 UICollectionViewFlowLayout 中的 invalidateLayout 似乎没有触发 collectionView 中的 sizeForItemAtIndexPath 方法?有任何想法吗?我真的只想在旋转时通过 sizeForItemAtIndexPath 调整列的大小。

注意:我在这里没有使用故事板,而是有一个自定义视图,我在其中放入 collection 视图并引用我自己的 collection 视图 类。

以下代码工作正常,但是在旋转时它并没有像它应该的那样将列数保持为 7。在 运行 上,代码最初控制台输出显示:

GCCalendar - init coder
GCCalendar - commonInit
GCCalendarLayout:invalidateLayout
GCCalendarLayout:invalidateLayout
ViewController:viewWillLayoutSubviews
GCCalendarLayout:invalidateLayout
GCCalendarLayout:prepareLayout
sizeForItemAtIndexPath
.
.
sizeForItemAtIndexPath
minimumInteritemSpacingForSectionAtIndex
minimumLineSpacingForSectionAtIndex
GCCalendarLayout:collectionViewContentSize
GCCalendarLayout:layoutAttributesForElementsInRect
GCCalendarLayout:collectionViewContentSize
ViewController:viewWillLayoutSubviews
GCCalendarCell:drawRect
.
.
GCCalendarCell:drawRect

但是旋转屏幕后我看到以下内容:

ViewController:viewWillLayoutSubviews
GCCalendarLayout:shouldInvalidateLayoutForBoundsChange
GCCalendarLayout:invalidateLayout
GCCalendarLayout:prepareLayout
GCCalendarLayout:collectionViewContentSize
GCCalendarLayout:layoutAttributesForElementsInRect
GCCalendarLayout:collectionViewContentSize

所以问题是 "sizeForItemAtIndexPath" 从未接到电话????

循环输出代码

注意:即使 "invalidateLayout" 为

,也不会触发 "sizeForItemAtIndexPath"

ViewController:viewWillLayoutSubviews GCCalendarLayout:shouldInvalidateLayoutForBoundsChange GCCalendarLayout:invalidateLayout

** 我的自定义视图包含 collection 视图 **

import UIKit

@IBDesignable class GCCalendarView: UIView {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }



    // Private

    private func commonInit() {
        if self.subviews.count == 0 {
            let bundle = NSBundle(forClass: self.dynamicType)
            let nib = UINib(nibName: "GCCalendarView", bundle: bundle)
            let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
            view.frame = bounds
            view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
            addSubview(view)
        }
    }

}

自定义Collection视图

import UIKit

class GCCalendar : UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {

    // Init ---------------

    func commonInit(coder aDecoder: NSCoder) {
        print("GCCalendar - commonInit")
        self.registerClass(GCCalendarCell.self, forCellWithReuseIdentifier: "GCCalendarCell")
        self.dataSource = self
        self.delegate = self

        let layout : GCCalendarLayout = GCCalendarLayout(coder: aDecoder)!
        self.setCollectionViewLayout(layout, animated: false)

        self.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        print("GCCalendar - init coder")
        super.init(coder: aDecoder)
        commonInit(coder: aDecoder)
    }


    // UICollectionViewDelegateFlowLayout ------------

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        print("sizeForItemAtIndexPath")
        let w : CGFloat = floor(self.frame.size.width/7)
        return CGSize(width: w, height: w)
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) ->
        CGFloat {
        print("minimumInteritemSpacingForSectionAtIndex")
        return 0.0
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
        print("minimumLineSpacingForSectionAtIndex")
        return 0.0
    }


    // UICollectionViewDataSource -------------------

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 21
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("GCCalendarCell", forIndexPath: indexPath) as? GCCalendarCell


        return cell!
    }
}

** 自定义 Collection查看单元格 **

import UIKit

class GCCalendarCell: UICollectionViewCell {

    @IBOutlet weak var title : UITextField!
    @IBOutlet weak var date: UILabel!

    required init?(coder aDecoder: NSCoder) {
        print("GCCalendarCell - init:coder")
        super.init(coder: aDecoder)
        commonInit()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    override func drawRect(rect: CGRect) {
        print("GCCalendarCell:drawRect")
        self.layer.borderWidth = 1
        self.layer.borderColor = UIColor.grayColor().CGColor
    }

    // Private

    private func commonInit() {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: "GCCalendarCell", bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
        view.frame = bounds
        view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        addSubview(view)
    }

}

自定义布局

import UIKit

class GCCalendarLayout : UICollectionViewFlowLayout {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
        print("GCCalendarLayout:shouldInvalidateLayoutForBoundsChange")
        return true
    }

    override func invalidateLayout() {
        print("GCCalendarLayout:invalidateLayout")
        super.invalidateLayout()

    }

    override func prepareForCollectionViewUpdates(updateItems: [UICollectionViewUpdateItem]) {
        print("GCCalendarLayout:prepareForCollectionViewUpdates")
        super.prepareForCollectionViewUpdates(updateItems)
    }

    override func finalizeCollectionViewUpdates() {
        print("GCCalendarLayout:finalizeCollectionViewUpdates")
        super.finalizeCollectionViewUpdates()
    }


}

如果你正在使用 Storyboard 设置 UICollectionviewFlowLayout Class 在 Storyboard 中我附在下面

编辑:在您的 viewController 中试试这个:

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) 
{
    (self.collectionview.collectionViewLayout).setItemSize(CGSizeMake(floor(size.width / 7), floor(size.width / 7)))
    self.collectionview.collectionViewLayout.invalidateLayout()
}

@Kujey 的解决方案可以应用于 UIView 而无需访问 UIViewController:

func traitCollectionDidChange(previousTraitCollection : UITraitCollection) {
    super.traitCollectionDidChange(previousTraitCollection)
    self.collectionView.collectionViewLayout.invalidateLayout()
}

现有答案对我没有任何帮助 (iPhone X Simulator iOS 11.2)。
我发现更改 estimatedSize 可以帮助我解决这个问题:

<...>
//***new line
flowLayout.estimatedItemSize = [self getIconSize];//get a new size for items

[flowLayout invalidateLayout];
<...>