【问题标题】:Use one index from array使用数组中的一个索引
【发布时间】:2016-07-15 13:49:50
【问题描述】:

我有一个集合视图,其中显示接下来四天的天气数据。在这个区块

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

这就是 x 的样子:

[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

我删除第一天并显示其他四个。从 JSON 我得到每三个小时的天气数据。这是一个数组,我想每天只显示一个数据。

有什么建议吗?

【问题讨论】:

  • 请添加您的 json 响应,以便轻松提取到这些收集单元格中

标签: arrays json swift uicollectionview


【解决方案1】:

在集合视图中,首先,您需要准备数据,然后使用UICollectionViewDataSource相应地填充它

您的数据应该是类变量,以便可以从类中的任何方法访问

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

这是你的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
    }
}

有简单的指南here。也尝试阅读更多关于UICollectionView的自定义单元格

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多