【问题标题】:UICollectionView reloadData not workingUICollectionView reloadData 不起作用
【发布时间】:2018-03-26 13:06:09
【问题描述】:

在获取使用的数据后,它在viewDidLoad 中被调用。 经过一些打印调试后,如果没有更改数据,它看起来会调用所有适当的委托方法。如果有一些数据发生变化,cellForItemAt 不会被调用。

重新加载整个部分可以正常工作。但是给了我一个不需要的动画。之前尝试禁用 UIView 动画,并在重新加载部分后启用,但仍然给了我一点动画。

collectionView.reloadSections(IndexSet(integer: 0)) 

这是我目前的情况,使用 reloadData() 时

UICollectionViewController 是 TabBarController 的一部分。 我正在使用自定义 UICollectionViewCells。数据从 CoreData 加载。

第一次打开标签,它工作正常。 在另一个选项卡中更新收藏夹项目并返回到此 collectionView 后,它没有更新。但是,如果我选择另一个选项卡,然后返回到这个选项卡,它就会更新。

var favorites = [Item]()


override func viewWillAppear(_ animated: Bool) {

    collectionView!.register(UINib.init(nibName: reuseIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)

    if let flowLayout = collectionView!.collectionViewLayout as? UICollectionViewFlowLayout {
        flowLayout.estimatedItemSize = CGSize(width: 1,height: 1)
    }

    loadFavorites()

}


func loadFavorites() {

    do {
        print("Load Favorites")

        let fetch: NSFetchRequest = Item.fetchRequest()
        let predicate = NSPredicate(format: "favorite == %@", NSNumber(value: true))
        fetch.predicate = predicate
        favorites = try managedObjectContext.fetch(fetch)

        if favorites.count > 0 {
            print("Favorites count: \(favorites.count)")
            notification?.removeFromSuperview()
        } else {
            showEmptyFavoritesNotification()
        }

        print("Reload CollectionView")

        collectionView!.reloadData(


    } catch {
        print("Fetching Sections from Core Data failed")
    }
}


override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    print("Get number of section, \(favorites.count)")
    if favorites.count > 0 {
        return favorites.count
    } else {
        return 0
    }
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    print("Get cell")

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SubMenuCell

    let menuItem = favorites[indexPath.row]

    cell.title = menuItem.title
    cell.subtitle = menuItem.subtitle

    return cell
}

控制台打印/日志

启动应用程序,转到没有收藏夹的 CollectionView 选项卡:

Load Favorites
Get number of section, 0
Get number of section, 0
Reload CollectionView
Get number of section, 0

切换选项卡,添加 Item 对象并将其设置为 true,然后返回 CollectionView 选项卡:

Load Favorites
Favorites count: 1
Reload CollectionView
Get number of section, 1

The datamodel has 1 item, reloading CollectonView, cellForRowAtIndex not called?

选择另一个选项卡,随机选择哪个选项卡,然后返回 CollectionView 选项卡,不更改任何数据。

Load Favorites
Favorites count: 1
Reload CollectionView
Get number of section, 1
Get cell

现在我的项目显示在列表中。您可以从 Get Cell 中看到 cellForItemAt 也被调用。这最后两次日志记录之间没有任何变化,只是在选项卡上单击了一次后退/第四次。

忘了提,但这段代码在模拟器中运行良好。 在读取设备上它只是没有给我任何错误,只是没有显示单元格(或调用cellForItemAt)

【问题讨论】:

  • 您能否更具体地说明什么不起作用,如果您已正确设置所有内容,那么在 collectionView 上调用 reloadData() 不会为每个可见的调用 cellForItemAtIndexPath项目(行)...

标签: ios swift uicollectionview


【解决方案1】:

我也遇到过这种问题,所以终于可以用这行代码解决了

[self.collectionView reloadData];

[self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathWithIndex:0]]];

【讨论】:

    【解决方案2】:
    var paths: [IndexPath] = []
    if !data.isEmpty {
        for i in 0...salesArray.count - 1 {
            paths.append(IndexPath(item: i, section: 0))
        }
        collectionView.reloadData()
        collectionView.reloadItems(at: paths)
    }
    

    这是帮助我解决此类问题的代码。

    【讨论】:

      【解决方案3】:

      好吧,也许我可以帮助别人=)

      我这样做:

      1. 从 API 加载数据
      2. 然后在加载数据后像这样调用 DispatchQueue.main.async

            DispatchQueue.main.async {
                self.pointNews = pointNews
            }
        
      3. 在self.pointNews didSet我尝试做collectionView.reloadData(),但它只工作,如果我在didSet中调用DispatchQueue.main.async

            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        

      【讨论】:

      • 遇到了同样的问题,有时我找回了单元格,有些则没有,然后我在 DispatchQueue.main.async 中重新加载了数据并且它工作了。
      【解决方案4】:

      在我的情况下,我的 collectionview 在 stackview 中,当我添加必要的约束时,我没有做任何约束。

      只需检查 collectionview 的约束。

      【讨论】:

        【解决方案5】:

        我在自我调整大小的单元格时遇到了同样的问题,上面的解决方案也可以,但是集合视图滚动位置会重置并转到顶部。以下解决方案有助于保持滚动位置。

        collectionView.reloadData()
        let context = collectionView.collectionViewLayout.invalidationContext(forBoundsChange: collectionView.bounds)
        context.contentOffsetAdjustment = CGPoint.zero
        collectionView.collectionViewLayout.invalidateLayout(with: context)
        collectionView.layoutSubviews()
        

        【讨论】:

          【解决方案6】:

          经过更多调试后,当项目减少(而不是像我上面尝试的那样增加)时,我得到了一个错误。

          UICollectionView received layout attributes for a cell with an index path that does not exist
          

          这导致了iOS 10 bug: UICollectionView received layout attributes for a cell with an index path that does not exist

          collectionView!.reloadData()
          collectionView!.collectionViewLayout.invalidateLayout()
          collectionView!.layoutSubviews()
          

          这解决了我的问题。

          我正在使用自动调整单元格大小,但我想这并不能解释为什么 cellForItemAt 没有被调用。

          【讨论】:

          • 我发现了同样的问题 cellForItemAt 没有调用你找到原因了吗?
          • 经过大量调试...完全被苹果激怒了。谢谢这么好的回答
          • 我最终只需要layoutSubviews,因为它单独称为 cellForItem 委托
          【解决方案7】:

          发布您的代码。

          一种可能性是您正在使用 `URLSession 并试图告诉您的集合视图从它的委托方法/完成闭包中更新,没有意识到该代码在后台线程上运行并且您不能从后台线程。

          【讨论】:

          • 我没有使用 URLSession。还尝试在后台和主线程中运行 reloadData() 。忘了写它在模拟器中工作,但不是在真实设备上。用代码更新了我最初的问题。
          • 永远不要在后台线程上更新 UI - 总是在主线程上。
          猜你喜欢
          • 1970-01-01
          • 2019-11-04
          • 2010-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多