【问题标题】:why is invalidateLayout is not triggering sizeForItemAtIndexPath in UICollectionView? (code attached)为什么 invalidateLayout 没有在 UICollectionView 中触发 sizeForItemAtIndexPath? (附代码)
【发布时间】:2016-01-12 09:47:04
【问题描述】:

问题是 collectionView 中的列数在旋转时不会保持在 7(所需数量)。需要修改什么代码来解决这个问题?

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

注意:我在这里没有使用故事板,而是有一个自定义视图,我在其中放入一个 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

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

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

** 自定义 CollectionView 单元格 **

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吗
  • 没有。不使用故事板
  • 我可以帮助你,但我不知道 swift。你会读 obj-c 吗?
  • 是的,应该没问题

标签: ios swift rotation uicollectionview uicollectionviewlayout


【解决方案1】:

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

【讨论】:

  • 我必须有这个权利,因为它确实在运行时正确设置了尺寸,它只是在旋转时出现问题
  • 可能是的。但是,您能否在自定义流程布局的 itemSize 函数中添加一个日志,以查看它是否在轮换时调用。
  • sizeForItemAtIndexPath (如果这就是你的意思)没有被调用轮换......这就是问题
【解决方案2】:

如果你正在使用 Storyboard 在 Storyboard 中设置 CollectionviewFlowLayout 类,我附上了 Bellow

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      @Kujey的解决方案可以应用到UIView而不访问UIViewController

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

      【讨论】:

      • @EricAya 我认为编程语言对于这个问题并不重要。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2021-08-05
      • 2016-06-19
      相关资源
      最近更新 更多