Search code examples
uitableviewswiftsections

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


Lets say that I have three arrays in my ViewController. Two of them represent section cells and one represents the sections.

How do I append a TableViewCell to a specific Section?

ViewController.swift:

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

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

Solution

  • A better approach would be to use a dictionary instead of separate arrays:

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

    Here the dictionary keys are the sections and the values arrays are the data for each section.

    So, a tableViewController might look like this:

    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
        }
    
    }
    

    Result:

    enter image description here