如何使用自定义 object 填充 table 视图?

How to populate table view with custom object?

我有一个符合 Codable 协议的结构体。我发出 URLSession 请求并收到 JSON 响应。我将响应编码到我的自定义结构中,看起来像这样。

struct Weather: Codable {
    let time: Date
    let location: String
    let timeEvents: [TimeEvents]
}  

struct TimeEvents: Codable {
    let validTime: Date
    let parameters: [Parameters]
}

struct Parameters: Codable {
    let name: String
    let unit: String
    let values: [Double]
}

我得到一个 object 天气。但是,在 object Weather 中,我想填充 validTime,即 01/01/2018 12:00,以及相应的 name 匹配 "temperature"和对应的values,10.5 C.

所以行看起来像:

[01/01/2018 12:00 : 10.5C]
[01/01/2018 13:00 : 11.5C]
[01/01/2018 14:00 : 11.6C]
.
.
.
[02/01/2018 00:00 : 3.1C]
[02/01/2018 01:00 : 3.1C]

在我的控制器中我有类似的东西:

var testWeatherObject : [Weather] = []

我只想在顶部显示一个 header,显示一个位置 ,即 纽约。

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return testWeatherObject[section].timeEvents.count
}

以上导致我的应用程序崩溃。我不确定如何获得正确的行数。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherDataCell", for: indexPath)

    return cell
}

你可以访问一个空数组所以

return testWeatherObject.first?.timeEvents.count ?? 0

如果你只想有一个部分,你不必设置这个。删除这些代码行:

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

现在,如果您想为每个 timeEvent 使用单个 table 视图单元格,您应该创建天气对象

var testWeatherObject = // your Weather object

并且在数据源方法 numberOfRowInSection 中只是说我想要与 testWeatherObject 具有 timeEvents 的单元格一样多

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return testWeatherObject.timeEvents.count
}

但是我建议不要将您的 Weather 对象用作变量。相反,您应该创建 TimeEvents 数组

var timeEvents = [/* your TimeEvents objects*/]

并且在 table 中查看数据源方法只使用这个

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return timeEvents.count
}

如果您没有部分,则无需实施 numberOfSections(in tableView: UITableView)

如果您只使用单个 Weather 对象,为什么不将 testWeatherObject 的定义更改为

var testWeatherObject = [TimeEvents]

然后你的numberOfRowsInSection就会变成

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return testWeatherObject.count
}

它正在崩溃,因为您试图访问一个空的嵌套数组。

我会先检查 testWeatherObjects.count 是否是 0。如果没有,那么您可以继续使用 testWeatherObject[section].timeEvents.count

故事板或 xib 中定义的单元格标识符是否匹配 "WeatherDataCell"?

我制作了一个简单的 tableview 应用程序示例。 https://github.com/y-okudera/TableViewDemoApp

希望对您有所帮助。