fellowProgrammer
fellowProgrammer

Reputation: 327

UICollectionView not loading fully until I scroll

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()
}

Upvotes: 6

Views: 4419

Answers (3)

pableiros
pableiros

Reputation: 16082

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
}

Upvotes: 1

fellowProgrammer
fellowProgrammer

Reputation: 327

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

Upvotes: 3

Damien
Damien

Reputation: 3362

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

Upvotes: 4

Related Questions