为什么invalidateLayout没有在UICollectionView中触发sizeForItemAtIndexPath? (已附加代码)

时间:2015-10-14 10:35:35

标签: ios swift rotation uicollectionview uicollectionviewlayout

问题是collectionView中的列数在旋转时不会保持在7(所需的数量)。修复此问题需要更改哪些代码?

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

注意:我不是在这里使用storyboard,而是我有一个自定义视图,我在其中放入collectionView并引用我自己的collectionView类。

以下代码工作正常,但是在轮换时它不会像预期的那样将列数保持为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

**我的自定义视图包含集合View **

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)
        }
    }

}

自定义收藏视图

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!
    }
}

** Custom CollectionView Cell **

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()
    }


}

4 个答案:

答案 0 :(得分:9)

编辑:在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()
}

答案 1 :(得分:1)

如果您正在使用Storyboard设置CollectionviewFlowLayout类在故事板中我附加了Bellow

this is FlowLayout

Classname Set here

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

现有答案(iPhone X Simulator iOS 11.2)对我没有任何帮助 我发现更改estimatedSize会对我有所帮助:

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

[flowLayout invalidateLayout];
<...>