【问题标题】:`numberOfItemsInSection` only being called after first item in array is added, limiting items to only one`numberOfItemsInSection` 仅在添加数组中的第一个项目后调用,将项目限制为一个
【发布时间】:2017-03-21 19:23:16
【问题描述】:

目前我有一个 UICollectionvView,它从相应的 UITableView 单元格中获取信息,如下所示:

//TableView
var knownForArray: [UIImage] = []
var knownForExtendedArray: [CastExtendedData] = []

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = peopleImagesTableView.dequeueReusableCell(withIdentifier: knownForCellIdentifier) as! KnownForCell

    print("Known for array count at cell:\(self.knownForArray.count)")

    cell.imageDelegete = self
    cell.knownForExtendedArray = self.knownForExtendedArray
    cell.knownForArray = self.knownForArray
    self.peopleImagesTableView.rowHeight = 150

    return cell
}

//CollectionView 

var knownForArray: [UIImage] = []
var knownForExtendedArray: [CastExtendedData] = []

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    print("Known for array count collectionview numberOfRowsInSection:\(self.knownForArray.count)")

    return knownForArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = knownForCollectionView.dequeueReusableCell(withReuseIdentifier: knownForReuseIdentifier, for: indexPath) as! KnownForCollectionViewCell

    if let knownPoster = knownForExtendedArray[indexPath.row].poster{

    DispatchQueue.main.async {

    print("collectionview knownForarray: \(self.knownForArray.count)")

    cell.knownForImages.sd_setImage(with: URL(string: "\(baseImageURL)\(knownPoster)"))
    }

  }
  return cell
}

通过添加print 语句,我可以看出,只要将第一项添加到tableview 的knownForArray。它会触发collectionview 的numberOfItemsInSection,从而将section 中的项目总数限制为1。tableview 的knownForArray 在完成检索所有JSON 数据后可以有50 多个项目。

【问题讨论】:

  • 当您向knownForArray 添加多于一项时会发生什么?您要达到的目标也不是很清楚。
  • 我试图让 collectionview 单元格的 numberOfItemsInSection 等于 knownForArray 的总数
  • 我认为问题是 numberOfItemsInSection 在 knownForArray 中的所有项目都被附加之前被调用得太快

标签: ios swift uitableview uicollectionview


【解决方案1】:

您需要在网络通话结束时拨打collectionView.reloadData()

【讨论】:

  • 补充一点,如果你把 reloadData() 放在异步 HTTP 请求中,强烈建议你在主线程上这样做,以便立即看到 UI 上的更改.像这样: DispatchQueue.main.async(execute: { () -> Void in self.collectionView.reloadData() })
  • @Jay 这不是推荐的,它是正常工作所必需的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
相关资源
最近更新 更多