7

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

}
Cœur
  • 37,241
  • 25
  • 195
  • 267
user3185748
  • 2,478
  • 8
  • 27
  • 43

1 Answers1

26

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:).

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
przemekblasiak
  • 475
  • 4
  • 9
  • But how do I create a Table View in a Storyboard then? Whenever I try to drag a UITableView to a view controller, even a blank UIVewController I'm met with something like this: https://imgur.com/vXBp3aS – user3185748 Dec 28 '14 at 23:54
  • It would be better for you to use UITableViewController directly, just drag it on the storyboard and in Identity Inspector change it's class to your UITableViewController subclass. I think the reason you can't drag a UITableView on a UIViewController is that you are zoomed out, double tap anywhere in the storyboard to zoom back in, and try again. – przemekblasiak Dec 29 '14 at 09:52