Swift 4.2:如何将Codable解析的JSON加载到TableView并获取多选数据?
没问题,我来一步步帮你搞定这两个需求!
一、把解析后的JSON数据加载到TableView
首先你需要在ViewController里准备好数据源和基础配置:
声明数据源数组
在你的ViewController类里添加一个可变数组来存储解析后的用户列表:var userLists: [UserList] = []完成JSON解析并更新数据源
假设你已经通过网络请求拿到了JSON数据(Data类型),用JSONDecoder解析后把数据赋值给数据源,然后刷新TableView(记得切回主线程):// 假设data是你获取到的JSON数据 do { let welcomeResponse = try JSONDecoder().decode(Welcome.self, from: data) self.userLists = welcomeResponse.userList // 必须在主线程刷新UI DispatchQueue.main.async { self.tableView.reloadData() } } catch { print("JSON解析失败: \(error.localizedDescription)") }实现TableView数据源方法
注册cell并实现UITableViewDataSource的核心方法:override func viewDidLoad() { super.viewDidLoad() // 注册默认cell(如果用自定义cell替换成你的cell类即可) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UserCell") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return userLists.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) let currentUser = userLists[indexPath.row] // 显示用户全名 cell.textLabel?.text = "\(currentUser.user.firstname) \(currentUser.user.lastname)" // 也可以附加显示userID,比如在detailTextLabel cell.detailTextLabel?.text = "ID: \(currentUser.userID)" return cell }
二、实现多选并获取选中项的用户名和userID
接下来搞定多选功能,步骤如下:
开启TableView多选模式
在viewDidLoad里开启多选:tableView.allowsMultipleSelection = true自定义选中状态(可选但更友好)
为了让用户直观看到选中状态,我们给cell添加勾选标记,需要实现两个代理方法:func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) cell?.accessoryType = .checkmark } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) cell?.accessoryType = .none } // 还要在cellForRowAt里恢复选中状态(防止cell复用导致状态丢失) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) let currentUser = userLists[indexPath.row] cell.textLabel?.text = "\(currentUser.user.firstname) \(currentUser.user.lastname)" cell.detailTextLabel?.text = "ID: \(currentUser.userID)" // 恢复选中状态 cell.accessoryType = tableView.indexPathsForSelectedRows?.contains(indexPath) == true ? .checkmark : .none return cell }获取所有选中项的信息
添加一个按钮(比如“确认选中”),点击时获取所有选中的用户信息:@IBAction func confirmSelection(_ sender: UIButton) { guard let selectedIndexPaths = tableView.indexPathsForSelectedRows else { print("没有选中任何用户") return } // 把选中的indexPath映射成对应的UserList对象 let selectedUsers = selectedIndexPaths.map { userLists[$0.row] } // 遍历输出或处理选中的信息 for user in selectedUsers { let fullName = "\(user.user.firstname) \(user.user.lastname)" let userId = user.userID print("选中用户: \(fullName), ID: \(userId)") // 这里可以把数据存入数组、上传服务器等 } }
这样就能完美实现你的需求啦!
内容的提问来源于stack exchange,提问作者devmikle
相关产品推荐
相关产品推荐

