1

I have a collection view where display weather data for the next four days. In this block

func prepareCollectionViewDataSource() {
        var x = self.city?.forecasts
        x?.removeFirst()
        self.otherDaysForecasts = x
    }

This is how x is looking like:

[0] : Forecast
      - temperature : 296.84199999999998 { ... }
      - maximum : 296.84199999999998 { ... }
      - minimum : 296.84199999999998 { ... }
      - description : "light rain" { ... }
      - icon : "10d" { ... }
      - humidity : 92.0 { ... }
      - pressure : 1021.4299999999999 { ... }
      - wind : 1.8600000000000001 { ... }
      - date : 2016-07-18 18:00:00 +0000

I remove the first day and display other four. From JSON I got weather data on every three hours. It's an array and I want to display only one data for each day.

Any suggestion how to do that?

John Deere
  • 35
  • 7

1 Answers1

1

In collection view, first, you need to prepare your data and then populate it accordingly using UICollectionViewDataSource

Your data should be class variables so it is accessible from any methods in class

var forcastData = [] // this is your x, array of dictionary

Here is your UICollectionViewDataSource

extension YourViewController : UICollectionViewDataSource {

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return forcastData.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
        // Here is the main part to configure the cell
        let data = forcastData[indexPath.row]
        // let say you have label for temparature that we want to set from your data in json dictionary
        cell.temperatureLabel.text = String(format: "%.2f MB", data.["temperature"].double!)
        return cell
    }
}

There is simple guide here. Also try read more on custom cell for the UICollectionView

Community
  • 1
  • 1
xmhafiz
  • 3,264
  • 1
  • 14
  • 21