【问题标题】:UITableView with Sections as Date from Json DataUITableView 的节作为来自 Json 数据的日期
【发布时间】:2018-07-14 20:53:50
【问题描述】:

我正在处理表格视图以呈现在 JSON 解析后收到的一些数据。我希望我的表格视图具有基于不同日期的部分。 JSON 中的每条记录都是一个事件,并且可以在一个日期发生多个事件。

这是我的 JSON 数据 https://get.rosterbuster.com/wp-content/uploads/dummy-response.json

我想像这样渲染我的表格视图 Table View with Sections as Date

到目前为止我做了什么:

我已经解析了以下结构中的数据

struct Roster : Codable {

    let flightnr: String?
    let date: String?
    let aircraftType: String?
    let tail: String?
    let departure: String?
    let destination: String?
    let departTime: String?
    let arrivalTime: String?
    let dutyID: String?
    let dutyCode: String?
    let captain: String?
    let firstOfficer: String?
    let flightAttendant: String?

    enum CodingKeys: String, CodingKey {
        case flightnr = "Flightnr"
        case date = "Date"
        case aircraftType = "Aircraft Type"
        case tail = "Tail"
        case departure = "Departure"
        case destination = "Destination"
        case departTime = "Time_Depart"
        case arrivalTime = "Time_Arrive"
        case dutyID = "DutyID"
        case dutyCode = "DutyCode"
        case captain = "Captain"
        case firstOfficer = "First Officer"
        case flightAttendant = "Flight Attendant"
    }  
}

我也设置了基本的表格视图,但不知道如何根据我上面附加的图像将检索到的数据分组到不同的部分。

任何帮助将不胜感激。

【问题讨论】:

  • 您是否使用任何本地存储,例如核心数据。如果是这样,您可以使用NSFetchedResultsController,您可以在其中按特定字段进行分组。如果不是,您将不得不自己使用UITableviewDataSource 方法来确定部分的数量和部分中每一行的内容
  • 是的,我正在使用核心数据持久性。有什么好的 NSFetchedResultsController 教程可以满足我的目的吗?
  • 恕我直言,花点时间阅读文档developer.apple.com/documentation/coredata/…NSFetchedResultsController 有一个初始化程序,它将 sectionNameKeyPath 作为参数。指定要分组的字段名称。循序渐进,先做一个有基础的示例项目,然后再解决您的具体问题
  • 非常感谢您的文档。我现在就试试。
  • @user1046037 我尝试了以下教程,效果很好。 andrewcbancroft.com/2015/03/05/… 再次感谢您的帮助 :)

标签: json swift uitableview


【解决方案1】:

这是我建议的方法:

1) 通过在基于日期属性的集合中映射 API JSON 响应来获取节数。这是您可以使用的东西(也许您也不需要将其转换为 Array 并且您想检查 date 是否不为零)

self.sections = Array(Set(self.dataModel.map({ (roster) -> String in
                roster.date!
            })))

2) 通过为每个部分创建一个名册数组来设置您的 rowsPerSection 数据模型。

//first set the array of sections.count dimension and empty array for each item
self.sections.forEach({ (string) in
    self.rowsPerSection.append([])
})
//then set each array
for index in 0..<self.sections.count {
    self.dataModel.forEach({ (roster) in
      if roster.date == self.sections[index] {
          self.rowsPerSection[index].append(roster)
        }
    })
}

这是我的虚拟代码,我用你的 URL 进行了测试,它可以工作:

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var dataModel = [Roster]()
    var sections = [String]()
    var rowsPerSection = [[Roster]]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        APICall { (rosters) in
            DispatchQueue.main.async {
                self.dataModel = rosters!
                self.sections = Array(Set(self.dataModel.map({ (roster) ->     String in
                roster.date!
                })))

                //first set the array of sections.count dimension and empty array for each item
                self.sections.forEach({ (string) in
                    self.rowsPerSection.append([])
                })
                //then set each array
                for index in 0..<self.sections.count {
                    self.dataModel.forEach({ (roster) in
                        if roster.date == self.sections[index] {
                            self.rowsPerSection[index].append(roster)
                        }
                    })
                }
                self.tableView.reloadData()
            }
        }
    }

    func APICall(onSuccess: @escaping(_ response: [Roster]?) -> Void) {
        let group = DispatchGroup()
        group.enter()

        DispatchQueue.global(qos: .default).async {
            let url = URL(string: "https://get.rosterbuster.com/wp-content/uploads/dummy-response.json")!
            let requestURL = URLRequest(url: url)
            let session = URLSession.shared
            session.dataTask(with: requestURL) { (data, response, error) in
                let decoder = JSONDecoder()
                let responseJson = try! decoder.decode([Roster].self, from: data!)
                onSuccess(responseJson)
                group.leave()
                }.resume()
            group.wait()
            return
        }
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        for index in 0..<sections.count {
            if index == section {
                return rowsPerSection[index].count
            }
        }
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = rowsPerSection[indexPath.section] [indexPath.row].destination

        return cell
    }

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

这是截图 -> screenshot

【讨论】:

  • 非常感谢。你已经做了很多工作。真的很有帮助。
猜你喜欢
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 2016-10-22
  • 1970-01-01
相关资源
最近更新 更多