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

标签 uitableview swift sections

假设我的 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"]

最佳答案

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

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
    }

}

结果:

enter image description here

关于uitableview - 如何将 TableViewCell 附加到 Swift 中的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29579554/

相关文章:

arrays - SWIFT 单元格填充

ios - 从 Firebase 查询创建 TableView (iOS、Swift)

ios - 从不同的文本字段在 [RETURN] 按键上执行不同的功能

swift - 如何访问数据模型 [字符串 : [String]] in UITableView with sections?

swift - 在 ios swift 中使用数组选择取消选择 uitableview 部分中的 radio

ios - 如何在 UISplitView 的详细 View 中清除 UIWebView 的内容

ios - UITableView 滚动时背景图像发生变化

ios - ios13-unSelectedItem的UITabBar tintColor不起作用

ios - 来自 xib 的自定义 View 通过界面生成器添加到 Controller - 保留自动布局约束并通过它们调整大小

ios - 在 UITableView 中包含选定单元格的部分之间滚动