繁体   English   中英

在cellForItemAt集合视图中不通过Swift 3中的collectionView.reloadData()更新indexPath

[英]In cellForItemAt collection view is not updating indexPath by collectionView.reloadData() in swift 3

我实际上想创建具有行和列的表,并使用UICollectionView进行此操作。 问题是重新加载或更新collectionView以添加或删除表中的行。 列和硬编码,即4。

我就是这样

  • 从情节提要中创建CollectionView
  • 加载页面后。 击中路线以获取数据
  • 提取数据后,将获取的数据保存在数组对象中。
  • 通过collectionView.reloadData()使用数组的大小更新集合视图。

从这里开始。 从情节提要中将集合视图引用到我的viewController

@IBOutlet weak var collectionView: UICollectionView!

然后在“ viewDidLoad”中。

self.collectionView.delegate = self
self.collectionView.dataSource = self

现在从服务器获得响应。 我正在更新我要从中创建行数的数组。 之后,这就是我重新加载collectionView的方式。

DispatchQueue.main.async
        {
            self.collectionView.collectionViewLayout.invalidateLayout()
            self.collectionView.reloadData()
            print("size of the array is(self.portfolioHandler.data.count)")
    }

在我的numberOfSections函数中。 我正在创建正确数量的单元格。 以及返回。

   func numberOfSections(in collectionView: UICollectionView) -> Int {
    var toReturn : Int = 1
    if (self.portfolioHandler != nil) {
        let data : [PortfolioData] = self.portfolioHandler.data!
        print("dataCount : \(data.count)")
        toReturn = data.count + 1
        print("toReturn : \(toReturn)")
    }
    return toReturn
}

随着日志,我得到返回的数字。 是正确的,并且正确返回了数据。

现在在我的cellForItem中有索引功能。 IndexPath没有更新。 它仍然是1.我正在创建的顶部标题。 下方没有细胞。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! MyCollectionViewCell
    print("section: \(indexPath.section) && row: \(indexPath.row)")

经过一切尝试。 没有任何帮助我获得要在我的collectionView中创建的正确单元格。

一个技巧可以起作用。 仅当我在开始时在numberOfSections中给出硬编码值时。 然后在服务器响应并重新加载collectionView之后,它将创建我上面上面硬编码的单元格数量,例如3或4。 没有更多的了。

但是我必须创建从服务器获取的单元格数量。 动态。

我花了很多时间。 请帮助我哪里我错了。 或如何解决这个问题。

经过所有尝试。 我无法解决集合视图的此重载问题。

但是我通过这个技巧在我的应用程序中处理了

第一次收集视图使单元格正确。 问题是重装。 因此,在进入此View Controller之前,我在以前的View Controller中提出了服务器请求。 并将响应发送到此View Controller。 这条路。 我有几个单元格要制作。 这样就行了。

但是作为一名学习者,我期待着这个重装问题的答案和真正的解决方案。

我将不胜感激。 虽然感谢@ɯɐɹʞ的意见。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM