gpt4 book ai didi

ios - 如何将 JSON 提取到 Swift 到 tableView 作为部分和行?

转载 作者:行者123 更新时间:2023-11-28 11:27:17 25 4
gpt4 key购买 nike

我想问一下如何实现文件,因为部分取决于 userId,然后在 tableview 中再次显示所有文件

我开始构建简单的项目,我获取 json 文件作为解码器并在表格 View 中显示所有内容

func fetchUsers(using url: String){
let url = URL(string: url)!
let _ = URLSession.shared.dataTask(with: url){ (data,response,error)
in
guard let data = data else {return}
do{
let objects = try JSONDecoder().decode([User].self, from: data) // decode * ( Codable )
self.users = objects
} catch{
print("error loading data cause: \(error)")
}
}.resume()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "users",for: indexPath) as? customeCellTableViewCell{
let indexRow = users[indexPath.row]
cell.dataModel(forModel: indexRow)
return cell
}
return UITableViewCell()
}



private func numberOfUsers(in users: [User]) -> Int {

return 1
}

func numberOfSections(in tableView: UITableView) -> Int {

return numberOfUsers(in: self.users)

}

最佳答案

就像@vadian 提到的那样应该避免使用元组,所以这是一个改进的解决方案。

我们可以使用结构来保存分组数据,而不是元组

struct UsersByID {
let id: Int
var users : [User]
}

然后将load函数改成

func load(withUsers users: [User]) {
let dict = Dictionary(grouping: users) { return $0.userID }
usersByID = dict.map { (key, values) in
return UsersByID(id: key, users: values)
}.sorted(by: { $0.id < $1.id })
}

其余代码相同,但将 key 替换为 id,将 value 替换为 users


旧的解决方案

首先创建一个字典来保存你的部分(键)和行(值)作为 View Controller 中的一个属性

var usersByID = [(key: Int, value: [User])]()

然后使用 grouping:by: 使用来自 json 的数组填充该字典

func load(withUsers users: [User]) {
usersByID = Dictionary(grouping: users, by: { user in
user.userID }).sorted(by: { $0.0 < $1.0})
}

然后 TableView 函数使用这个字典


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

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

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

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

let user = usersByID[indexPath.section].value[indexPath.row]
cell.textLabel?.text = user.title
//...

return cell
}

关于ios - 如何将 JSON 提取到 Swift 到 tableView 作为部分和行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57830921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com