How to create UITableViewCell with different UITableViewCellStyle?

Before I describe the issue I faced and how I solved it, here are a few resources regarding UITableViewCell style.

  • UITableView is the built-in control of iOS to create tables with a comprehensive set of delegate methods giving developers the option to customize.
  • UITableViewCell represents each row in a UITableView in iOS.
  • UITableViewCellStyle represents the different styles a row can be initialized in. The default value for this is , surprise, .Default. More details on what each of them indicate is here

There are 2 ways in which you can specify the type of UITableViewCell that you want to use for your UITableView:

  1. If you have only one type of cell in uitableview then you can use the following code in the uitableviewdelegate:cellForRowAtIndexPath

    With this method it is pretty straightforward to change the style of the uitableview cell to the desired value.
  2. The second, and more commonly used method, involves 2 steps:
    1. First, register the cell types that you are going to use in your uitableview in the viewDidLoad() method of you uitableviewcontroller
    2. Second, in uitableviewdelegate:cellForRowAtIndexPath, add the below method to use the registered cell class

      In this second method there is no straightforward way to change the style of the UITableViewCell as it was in previous method.

So when I was faced with this issue, I figured, this seems to be a pretty simple thing, Swift should have provided me a way with changing the cell style. I searched far and wide in stackoverflow.com and the only option is to create a new custom cell derived from UITableViewCell and override the constructor to change style if you are following the second method of initialization

So below is the sample custom cell to create a uitableview cell with .SubTitle style

Hopefully this will save you some time in trying to figure out if a simpler way exists

How to create UITableViewCell with different UITableViewCellStyle?