Swift:如何在设备旋转后刷新UICollectionView布局


72

我使用UICollectionView(flowlayout)构建简单的布局。每个单元格的宽度设置为使用self.view.frame.width

但是当我旋转设备时,单元格不会更新。

在此处输入图片说明

我找到了一个函数,该函数在方向改变时被调用:

override func willRotateToInterfaceOrientation(toInterfaceOrientation: 
  UIInterfaceOrientation, duration: NSTimeInterval) {
    //code
}

但我找不到更新UICollectionView布局的方法

主要代码在这里:

class ViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{

    @IBOutlet weak var myCollection: UICollectionView!

    var numOfItemsInSecOne: Int!
    override func viewDidLoad() {
        super.viewDidLoad()

        numOfItemsInSecOne = 8
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {

        //print("orientation Changed")
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

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

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

        return cell
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
    let itemSize = CGSize(width: self.view.frame.width, height: 100)
    return itemSize
    }}

Answers:


77

添加此功能:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews() 
    myCollection.collectionViewLayout.invalidateLayout()
}

更改方向时,将调用此功能。


2
UICollectionViewController已经具有collectionView属性,因此您可以按照我所说的那样调用它们。只需将它们编辑为collectionView.reloadData()。它将起作用。
appiconhero.co 2016年

2
因此,您需要重新加载视图,不仅可以触发布局刷新吗?
Rivera

2
检查@kelin的答案.invalidateLayout()很有道理。
thesummersign

1
viewDidLayoutSubviews回到肖像时,我的应用程序崩溃了,因为旧的布局单元太大。viewWillLayoutSubviews 完美地工作
jfgrang

2
使用此应用后,应用会在应用启动时挂起。
rv7284

59

更好的选择是调用,invalidateLayout()而不是reloadData()因为它不会强制重新生成单元,所以性能会稍好一些:

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews() 
    myCollection.collectionViewLayout.invalidateLayout()
}

这是正确的方法。这应该是公认的答案。
sumsumsign

这是正确的方法。.不必再次重新加载数据
Abdul Waheed

8
这让我暗恋。当我在viewDidLayoutSubviews函数中放置打印语句时,就会识别出无限循环。
nyxee

2
@nyxee,viewWillLayoutSubviews然后尝试。我敢打赌,您的集合视图是视图控制器的视图?如果是这样,我建议将其包装到另一个视图中。
凯琳

6
如果使用UICollectionViewController,则会发生无限循环,因为在这种情况下,collectionView它也是控制器的视图。因此,如果您更改collectionView布局viewWillLayoutSubviews,则会调用相关方法。
凯琳'18

16

您也可以通过这种方式使其无效。

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    [self.collectionView.collectionViewLayout invalidateLayout]; 
}

13

viewWillLayoutSubviews()对我不起作用。viewDidLayoutSubviews()都没有。两者都使应用程序进入无限循环,我使用打印命令进行了检查。

工作的方法之一是

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
// Reload here
}

14
别忘了致电super.viewWillTransition...
d4Rk

13

要更新UICollectionViewLayouttraitCollectionDidChange也可以使用方法:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    guard previousTraitCollection != nil else { return }
    collectionView?.collectionViewLayout.invalidateLayout()
}

2
这对我来说最有效,所需的方法实际上取决于您的CollectionView应用程序,在我的实例中,与其他解决方案相比,它与自定义FlowLayout的其他行为更兼容,因为我的商品都具有相同的大小,具体取决于traitCollection
火箭花园

2
出色-在实例化自定义UITableViewCell中的UICollectionView时也可以使用。
DrWhat

7

UICollectionLayout检测到边界变化时,它询问是否需要重新布线无效布局。您可以直接重写该方法。UICollectionLayout可以invalidateLayout在正确的时间调用方法

class CollectionViewFlowLayout: UICollectionViewFlowLayout{

    /// The default implementation of this method returns false.
    /// Subclasses can override it and return an appropriate value
    /// based on whether changes in the bounds of the collection
    /// view require changes to the layout of cells and supplementary views.
    /// If the bounds of the collection view change and this method returns true,
    /// the collection view invalidates the layout by calling the invalidateLayout(with:) method.
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {

        return (self.collectionView?.bounds ?? newBounds) == newBounds
    }
}

3

您可以通过使用更新UICollectionView布局

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if isLandscape {
        return CGSizeMake(yourLandscapeWidth, yourLandscapeHeight)
    }
    else {
        return CGSizeMake(yourNonLandscapeWidth, yourNonLandscapeHeight)
    }
}

3

通话viewWillLayoutSubviews不是最佳的。尝试先调用该invalidateLayout()方法。

如果遇到The behaviour of the UICollectionViewFlowLayout is not defined错误,则需要根据新布局验证视图中的所有元素是否都已更改其大小。(请参见示例代码中的可选步骤)

这是代码,可以帮助您入门。根据创建UI的方式,您可能必须尝试找到合适的视图来调用该recalculate方法,但这应该可以指导您迈出第一步。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

    super.viewWillTransition(to: size, with: coordinator)

    /// (Optional) Additional step 1. Depending on your layout, you may have to manually indicate that the content size of a visible cells has changed
    /// Use that step if you experience the `the behavior of the UICollectionViewFlowLayout is not defined` errors.

    collectionView.visibleCells.forEach { cell in
        guard let cell = cell as? CustomCell else {
            print("`viewWillTransition` failed. Wrong cell type")
            return
        }

        cell.recalculateFrame(newSize: size)

    }

    /// (Optional) Additional step 2. Recalculate layout if you've explicitly set the estimatedCellSize and you'll notice that layout changes aren't automatically visible after the #3

    (collectionView.collectionViewLayout as? CustomLayout)?.recalculateLayout(size: size)


    /// Step 3 (or 1 if none of the above is applicable)

    coordinator.animate(alongsideTransition: { context in
        self.collectionView.collectionViewLayout.invalidateLayout()
    }) { _ in
        // code to execute when the transition's finished.
    }

}

/// Example implementations of the `recalculateFrame` and `recalculateLayout` methods:

    /// Within the `CustomCell` class:
    func recalculateFrame(newSize: CGSize) {
        self.frame = CGRect(x: self.bounds.origin.x,
                            y: self.bounds.origin.y,
                            width: newSize.width - 14.0,
                            height: self.frame.size.height)
    }

    /// Within the `CustomLayout` class:
    func recalculateLayout(size: CGSize? = nil) {
        estimatedItemSize = CGSize(width: size.width - 14.0, height: 100)
    }

    /// IMPORTANT: Within the `CustomLayout` class.
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {

        guard let collectionView = collectionView else {
            return super.shouldInvalidateLayout(forBoundsChange: newBounds)
        }

        if collectionView.bounds.width != newBounds.width || collectionView.bounds.height != newBounds.height {
            return true
        } else {
            return false
        }
    }

3

这个对我有用。这是Objective-C中的代码:

- (void)viewDidLayoutSubviews {
  [super viewDidLayoutSubviews];
  [collectionView.collectionViewLayout invalidateLayout];
}

3

请明白这一点

旋转iPad时,不会在iPad上调用traitCollectionDidChange(previousTraitCollection :),因为在纵向和横向方向上size类都是.regular。每当集合视图大小更改时,都会调用viewWillTransition(to:with :)。

另外,如果您的应用程序支持多任务处理,则不应使用UIScreen.mainScreen()。bounds,因为它可能不会占据整个屏幕,因此最好使用collectionView.frame.width。



2

我也遇到了一些问题,但是随后使用以下命令解决了问题:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        collectionViewFlowLayoutSetup(with: view.bounds.size.width)
        collectionView?.collectionViewLayout.invalidateLayout()
        collectionViewFlowLayoutSetup(with: size.width)
    }

    fileprivate func collectionViewFlowLayoutSetup(with Width: CGFloat){

        if let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout {
            flowLayout.estimatedItemSize = CGSize(width: Width, height: 300)
        }

    }

2

我通过在屏幕方向发生变化时设置通知并重新加载根据屏幕方向设置项目大小并为上一个单元格设置索引路径的单元格来解决此问题。这也适用于flowlayout。这是我写的代码:

var cellWidthInLandscape: CGFloat = 0 {
    didSet {
        self.collectionView.reloadData()
    }
}

var lastIndex: Int = 0

override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.dataSource = self
    collectionView.delegate = self
    NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
    cellWidthInLandscape = UIScreen.main.bounds.size.width

}
deinit {
    NotificationCenter.default.removeObserver(self)
}
@objc func rotated() {

        // Setting new width on screen orientation change
        cellWidthInLandscape = UIScreen.main.bounds.size.width

       // Setting collectionView to previous indexpath
        collectionView.scrollToItem(at: IndexPath(item: lastIndex, section: 0), at: .right, animated: false)
}
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

   // Getting last contentOffset to calculate last index of collectionViewCell
    lastIndex = Int(scrollView.contentOffset.x / collectionView.bounds.width)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // Setting new width of collectionView Cell
        return CGSize(width: cellWidthInLandscape, height: collectionView.bounds.size.height)

}

0

我使用以下方法解决了问题

override func viewDidLayoutSubviews() {
        if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            collectionView.collectionViewLayout.invalidateLayout()
            collectionView.collectionViewLayout = flowLayout
        }
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.