How do I populate two sections in a tableview with two different arrays using swift?

Woody picture Woody · Apr 11, 2015 · Viewed 77.9k times · Source

I have two arrays Data1 and Data2 and I want to populate the data within each of these (they contain strings) into a tableview in two different sections.

The first section should have a heading "Some Data 1" and the second section should be titled "KickAss".

I have both sections populating with data from the first array (but with no headings either).

Here is my code so far:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 2
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var rowCount = 0
    if section == 0 {
        rowCount = Data1.count
    }
    if section == 1 {
        rowCount = Data2.count
    }
    return rowCount
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
    let ip = indexPath
    cell.textLabel?.text = Data1[ip.row] as String
    return cell
}

in the cellForRowAtIndexPath method, is it possible for me to identify the section somehow like I did in the numberOfRowsInSection method?

Also, how do I give titles to each section?

Answer

ABakerSmith picture ABakerSmith · Apr 11, 2015

TableView Cells

You could use a multidimensional array. For example:

let data = [["0,0", "0,1", "0,2"], ["1,0", "1,1", "1,2"]]

For the number of sections use:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return data.count
}

Then, to specify the number of rows in each section use:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data[section].count
}

Finally, you need to setup your cells:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellText = data[indexPath.section][indexPath.row]

    //  Now do whatever you were going to do with the title.
}

TableView Headers

You could again use an array, but with just one dimension this time:

let headerTitles = ["Some Data 1", "KickAss"]

Now to set the titles for the sections:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section < headerTitles.count {
        return headerTitles[section]
    }

    return nil
}

The code above checks to see there's a title for that section and returns it, otherwise nil is returned. There won't be a title if the number of titles in headerTitles is smaller than the number of arrays in data.

The Result

enter image description here