如何将 TableViewCell 附加到 Swift 中的特定部分

How do I append a TableViewCell to a specific Section in Swift

假设我的 ViewController 中有三个数组。其中两个代表section cells,一个代表sections。

如何将 TableViewCell 附加到特定部分?

ViewController.swift:

// represents my 2 sections
var sectionNames = ["Switches","Settings"]

// data for each section
var switchData = ["switch1","switch2", "switch3"]
var settingData = ["setting1", "setting2"]

更好的方法是使用字典而不是单独的数组:

let data: Dictionary<String,[String]> = [
    "Switches": ["switch1","switch2","switch3"],
    "Settings": ["setting1","setting2"]
]

这里的字典键是部分,值数组是每个部分的数据。

因此,tableViewController 可能如下所示:

class MyTableViewController: UITableViewController {
    let data: Dictionary<String,[String]> = [
        "switches": ["switch1","switch2","switch3"],
        "settings": ["setting1","setting2"]
    ]

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // Return the number of sections.
        return data.count
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section.
        let sectionString = Array(data.keys)[section]

        return data[sectionString]!.count
    }

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let sectionString = Array(data.keys)[section]
        return sectionString
    }

    override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! UITableViewCell

        // Configure the cell...
        let sectionString = Array(data.keys)[indexPath.section]
        cell.textLabel?.text = data[sectionString]![indexPath.row]

        return cell
    }

}

结果: