ios - 如何让每个 UITableViewOption 都有自己的数据
问题描述
我试图让我的 UITableView 中的每个选择都有自己独特的数据集。例如,在我的表格视图中,我有一个州列表,然后当我单击一个州时,我希望每个州都有一个与其具体对应的城市列表。我在下面附上了我的代码,该代码仅适用于 UITableView。如果您可以请在答案中包含代码以及将其放置在哪里会有所帮助,我已经尝试了一段时间。我是 Xcode/swift 的新手,我会一步一步地欣赏它。谢谢 !
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let textCellIdentifier = "TextCell"
var states = ["Illinois", "Indiana", "Kentucky", "Michigan", "Ohio", "Pennsylvania", "Wisconsin"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return states.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath)
let row = indexPath.row
cell.textLabel?.text = states[row]
return cell
}
private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let row = indexPath.row
print(states[row])
}
解决方案
您可以像这样构建数组模型
struct MainItem {
var name:String
var cities:[String]
init(name:String,cities:[String]) {
self.name = name
self.cities = cities
}
}
//
let item1 = MainItem(name:"Illinois",cities:["city1","city2"])
let item2 = MainItem(name:"Indiana",cities:["city3","city4"])
var states = [item1,item2]
//
在cellForRowAt
cell.textLabel?.text = states[row].name
//
在didSelectRowAtIndexPath
let cities = states[row].cities
推荐阅读
- python - 对于一列的所有唯一“单词”,从另一列中查找唯一单元格,然后在 python 中平均另一列的对应值
- hyperlink - 在我的 HTML 中插入会员跟踪链接
- android - 在 AOSP 上设置蓝牙呼叫转移?(首选 AOSP 7)
- azure - Private Endpoint Azure DevOps
- angular - 我的 Angular 6 项目未能构建。node_modules/@angular/core/core.d.ts(12620,86):错误 TS1110:预期类型
- python - 有没有办法从 Keithley SourceMeter 读取电流值到我的计算机上?
- sql - 如何用 SQL 中的表更新数据库表
- c++ - 从链表中删除节点
- typescript - keyof typeof 模块不适用于接口
- selenium - 使用 Selenium 实现 Microsoft Teams 桌面应用程序自动化