【问题标题】:How to populate UITableView with data from a grouped struct in a dictionary?如何使用字典中分组结构的数据填充 UITableView?
【发布时间】:2018-02-28 11:50:09
【问题描述】:

我有以下结构,其中包含来自已解析 JSON 的数据。

struct callRailData {
var callDate: String
var userDetails = callData()
}

struct callData{
var callerName: String?
var callerNumber: String?
var callerCityName: String?
var callerCountryName: String?
var callerStateName: String?
var callAnsweredState: Bool?
var callDirection: String?
var callDuration: String?
var callRecordingURL: String?
var callRecordingPlayer: String?
var callSource: String?
var callCompanyName: String?
}

我需要在 UITableView 中显示这些数据,并将“callDate”作为部分标题。所以我在这本字典中对结构进行了分组:

var user = [callRailData]()

var sections = Dictionary<String, [callRailData]>()
sections = Dictionary(grouping: user, by: { $0.callDate }). 

我不知道如何在 tableview 中显示这些数据。如何从“sections”中获取 numberOfSections 和 numberOfRowsInSection。 请帮助我是 Swift 和 iOS 开发的初学者。

【问题讨论】:

  • 按照本教程在 Swift 中的 tableview 上填充数据:codementor.io/brettr/…
  • 我知道如何在 tableview 中填充数据。在这种特殊情况下,我的 numberOfSections 和 numberOfRowsInSection 有问题。
  • 您不应该使用字典作为表格视图的来源,因为它不会保持条目排序(例如通过索引访问)。最好使用数组。
  • 我需要用相同的“callDate”对数据进行分组以显示在部分中,所以我不得不使用字典。有其他选择吗?
  • 您可以使用 Brian youtube.com/watch?v=poUZnT7N-Vk 在这里最好描述的新分组功能,仅从这里开始只有 9 分钟 :-)

标签: ios swift uitableview dictionary struct


【解决方案1】:

一般来说,我们使用数组作为tableview的数据源。提供 numberOfRows= 数组计数和数组中的“cellForRow”数据源对象。

【讨论】:

    【解决方案2】:

    我认为您不需要像那样进行分组.. 就这样做吧,希望它会奏效。

      override func numberOfSections(in tableView: UITableView) -> Int {
          return user.count
        }
    

    它会根据您的用户数量来划分部分。 现在在每个部分中获取一行来显示数据。

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
               return 1
            }
    
    
    
     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "your cell", for: indexPath) as! Your Cell class
             cell.callerNameLabel.text = user[indexpath.section].userdetails.callerName 
            return cell
        }
    

    这个函数将设置你的秒头标题

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
           return user[section].callDate
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      • 2019-03-06
      • 2015-04-08
      相关资源
      最近更新 更多