微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在节标题下创建tableview子标题时出现问题|迅速

如何解决在节标题下创建tableview子标题时出现问题|迅速

本质上,我想在tableview tableview中创建一个子头,以进一步将以下JSON数据分组。

目前,数据仅按JSON中的date字符串进行分组,但我需要进一步上一层,并按customer标头下的type进行分组。

标题层次结构:

Date
  Customer

JSON示例:

[
  {
    "date": "November 12 2020","customer": "Customer1","num": "123","type": "Dark2"
  },{
    "date": "November 12 2020","customer": "Customer2","num": "7678","type": "Dark1"
  },"customer": "Customer5","num": "089786","type": "Dark9"
  },"customer": "Customer8","num": "7689","type": "Dark4"
  }
]

JSON函数

 private func fetchJSON() {
        guard let url = URL(string: "https://example.com"),let value = name.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
            else { return }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "person=\(value)".data(using: .utf8)
        
        URLSession.shared.dataTask(with: request) { data,_,error in
            guard let data = data else { return }
            
            
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let res = try decoder.decode([RecordStruct].self,from: data)
                let grouped = Dictionary(grouping: res,by: { $0.date })
                var keys = grouped.keys.sorted()
                if let index = keys.firstIndex(of: "") {
                    let first = keys.remove(at: index)
                    keys.insert(first,at: 0)
                }

                self.sections = keys.map({RecordStructSection(name: $0,items: grouped[$0]!)})
                
                dispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
            catch {
                print(error)
            }
            
            }.resume()
        
    }


struct RecordStructSection {
    let name : String
    var items : [RecordStruct]
}

    struct RecordStruct: Decodable {
        let date: String
        let customer: String
        let num: String
        let type: String
        
        enum CodingKeys : String,CodingKey {
            case date,customer,num,type
        }
    
    }

我正在执行以下操作以显示标题部分:

var sections = [RecordStructSection]()
var structure = [RecordStruct]()

override func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
    

return "\(sections[section].items.count)  \(sections[section].date)" }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。