Tometoyou
Tometoyou

Reputation: 8376

Best way to structure view controller with different use cases?

I have a UITableViewController that I'm using in a number of different ways:

  1. Display multiple custom cells (let's call these CellX), inside a UIPageViewController parent.
  2. Display a single CellX cell, with its own navigation bar title.
  3. Display a different set of custom cells (CellY).
  4. Display multiple CellX cells but using different data.

At the moment, I have boolean variables set that are set to identify that the UITableViewController is being used in one of the use cases, and have quite a few if statements to control what's happening inside the UITableViewController. However, this seems to be such a bad way of coding, there's got to be better way?

Upvotes: 2

Views: 119

Answers (3)

Ben Sullivan
Ben Sullivan

Reputation: 2154

There are a few ways this can be achieved, I recommend using an enumeration for all the possible states of the view and then switch on this in the relevant table method. Something like the below:

enum TableState {

  case Full
  case Filtered
  case Advanced
  case SecondView
}

var tableState = TableState.Full

switch tableState {

  case .Full: //setup table
  case .Filtered
  case .Advanced
  case .SecondView
}

Upvotes: 1

Jack
Jack

Reputation: 11

Not knowing your full design, but from what you put, I would use enums and a case statement to make your code easier to understand and maintain.

Upvotes: 1

Frane Poljak
Frane Poljak

Reputation: 2365

You can create some enum type to determine your context and then inside a switch statement populate the view for each case (and put those cases in separate methods so it's more understandable). Switch statement is not only more readable, but much better at performance. The other way would be to create few different viewContollers if your contexts are drastically different.

Upvotes: 1

Related Questions