4
votes

I have a collection view that I want to display hourly weather in. I seem to have a problem with loading the cell, and for some reason scrolling forwards and then back loads the cell fully. Before I scroll the collection view, all of the constraints do not work and one label doesn't show it's info.

Before scrolling Before scrolling

After scrolling (this is how I want the cells to look like) After scrolling (this is how I want the cells to look like)

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()
}
3
to know what is the problem i might need some codezombie
Without code and further information of the constraints, this question can't be answered.vikingosegundo
updated question @vikingosegundofellowProgrammer
reloading the collection view will populating the cells doesnt seem to be a good idea to me.vikingosegundo
but hey: you are doing it after return, so it will be never executed.vikingosegundo

3 Answers

3
votes

Seems like you populate your cells asynchronously, if so then add a mycollectionview.reloadData() at the end.

3
votes

I fixed the problem by adding cell.layoutIfNeeded() before the return cell. Everything loaded as expected without any scrolling!

0
votes

I had the same issue and I solved calling cell.layoutIfNeeded() inside collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath).

Also if you are using UICollectionViewDiffableDataSource and you are applying the snapshot inside the viewWillAppear, you need to add some delay to make it work correctly like this:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
    // apply here the snapshot
}