Programmatically Create Grouped UITableView

user3185748 picture user3185748 · Dec 28, 2014 · Viewed 15.7k times · Source

I have a UITableViewController that currently displays 4 cells that will always be displayed and would like to group them together however I can't figure out how. The resources I have found only give instructions using Interface Builder when a standard UITableView is inserted over a UIViewController or something of the like. How can I group them programmatically?

Here is my current UITableViewController class:

import UIKit

class SecondViewController: UITableViewController {

    let Items = ["Altitude","Distance","Groundspeed"]

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.Items.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
        cell.textLabel?.text = self.Items[indexPath.row]
        return cell
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

}

Answer

przemekblasiak picture przemekblasiak · Dec 29, 2014

Table view's style is set in the moment of initialization, and can't be modified later, but what you could do is to create a new table view with the grouped style you want and set it as your table view in viewDidLoad():

    self.tableView = UITableView(frame: self.tableView.frame, style: .grouped)

You should also specify a number of sections in the table using numberOfSectionsInTableView(_:) and the titles for each of them using tableView(_:titleForHeaderInSection:) or tableView(_:titleForFooterInSection:).