首页 > 解决方案 > 如何让每个 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])
    }

标签: iosswift

解决方案


您可以像这样构建数组模型

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

推荐阅读