假设我的ViewController中有三个数组。其中两个表示节单元格,一个表示节。
如何将TableViewCell附加到特定的部分?
ViewController.swift :
// represents my 2 sections
var sectionNames = ["Switches","Settings"]
// data for each section
var switchData = ["switch1","switch2", "switch3"]
var settingData = ["setting1", "setting2"]
答案 0 :(得分:1)
更好的方法是使用字典而不是单独的数组:
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
}
}
结果: