Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programatically adding sections and cells to Table View Swift

Say I have a list/array of sections:

let sections = [new Section("today", todaylist), 
                new Section("yesterday", yestlist), 
                new Section("25th February", list25f),...]

As you can see each section has a section name and a list of objects which will populate the cells inside that particular section.

For now, let's say these objects are just simple strings.

How would I programmatically loop through sections and create a new section with the appropriate title and the appropriate number of cells.

I.e- the number of cells for section no. i would be:

sections[i].getList().count

in the case of "today" that would be equivalent to

todaylist.count

I can't add the sections in the storyboard because it will vary, the table view will be dynamic !

Thanks for any help !

like image 297
Greg Peckory Avatar asked Jun 30 '15 12:06

Greg Peckory


People also ask

How do I add a section in Swift?

To add a section around some cells, start by placing a Section around it, optionally also adding a header and footer. As an example, we could create a row that holds task data for a reminders app, then create a list view that has two sections: one for important tasks and one for less important tasks.


1 Answers

Check out this code:

import UIKit

class TableViewController: UITableViewController {

    var names = ["Vegetables": ["Tomato", "Potato", "Lettuce"], "Fruits": ["Apple", "Banana"]]

    struct Objects {

        var sectionName : String!
        var sectionObjects : [String]!
    }

    var objectArray = [Objects]()

    override func viewDidLoad() {
        super.viewDidLoad()

        for (key, value) in names {
            println("\(key) -> \(value)")
            objectArray.append(Objects(sectionName: key, sectionObjects: value))
        }
    }

    // MARK: - Table view data source

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

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


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

        // Configure the cell...
        cell.textLabel?.text = objectArray[indexPath.section].sectionObjects[indexPath.row]
        return cell
    }

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        return objectArray[section].sectionName
    }
}

Hope it will help you.

Reference from my old answer.

like image 111
Dharmesh Kheni Avatar answered Oct 19 '22 22:10

Dharmesh Kheni