UICollectionView在滚动之前无法完全加载

6
我有一个集合视图,想要在其中显示每小时的天气。我似乎遇到了加载单元格的问题,而且出现了向前滚动再返回会完全加载单元格的情况。在我滚动集合视图之前,所有约束都不起作用,一个标签也没有显示它的信息。 滚动前 滚动前 滚动后(这就是我希望单元格看起来的样子) 滚动后(这就是我希望单元格看起来的样子)
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return newhourlyWeather.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! hourlyWeatherCell

    // Configure the cell

    let hWeather = newhourlyWeather[indexPath.row]

    if let HourlyTemp = hWeather.temperatureh {
        cell.temperatureHLabel.text = "\(HourlyTemp)º"
    }

    if let HourlyTime = hWeather.convertedTimeH {
        cell.timeHLabel.text = "\(HourlyTime)"
    }

    if let HourlyRain = hWeather.precipProbabilityh {
        cell.rainChanceHLabel.text = "\(HourlyRain)%"
    }

     cell.iconhView.image = hWeather.iconh

    return cell

    self.collectionView.reloadData()
}

要了解问题是什么,我可能需要一些代码。 - zombie
没有代码和更多的限制信息,这个问题无法回答。 - vikingosegundo
更新的问题 @vikingosegundo - fellowProgrammer
重新加载集合视图来填充单元格对我来说似乎不是一个好主意。 - vikingosegundo
但是嘿:你在返回后执行它,所以它永远不会被执行。 - vikingosegundo
显示剩余2条评论
3个回答

4
似乎您是异步填充单元格,如果是这样,请在末尾添加mycollectionview.reloadData()。

3
我通过在 return cell 之前添加 cell.layoutIfNeeded() 来解决了问题。一切都按预期加载,没有任何滚动!

我认为你遇到了约束问题。 - Jeff

1
我遇到了同样的问题,我在 collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) 中调用 cell.layoutIfNeeded() 解决了这个问题。
此外,如果你正在使用 UICollectionViewDiffableDataSource 并且你正在 viewWillAppear 中应用 snapshot,你需要添加一些延迟以使其正常工作,像这样:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
    // apply here the snapshot
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接