H.Jass
H.Jass

Reputation: 3

Multiple UITableViewCell types programmatically

I am writing an app in Swift 4 programmatically.

I'd like to create a settings page that would contain a UITableView, however the rows in this will contain different types of content.

For example, I'd like a row that has a slider, a row that has a uiswitch, a row that contains a text input and so on.

I imagine the approach for this, is to create a custom cell class for each type of cell I would like to use?

However, currently I create my cells as such :

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! CustomCell
    cell.rowContent.text = items[indexPath.row]
    cell.tableViewController = self
    return cell
}

How can I downcast my cell based on it's content?

Upvotes: 0

Views: 1924

Answers (1)

Abdoelrhman
Abdoelrhman

Reputation: 916

Looks like you're trying to do a form, if so I'd suggest Eureka

otherwise you'd register the cell, then dequeue your cell of choice depending on index or any other factor you'd like :

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch indexPath.section{
    case 1:
         let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! CustomCell
    cell.rowContent.text = items[indexPath.row]
    cell.tableViewController = self
    return cell 
    case 2:
    let cell = tableView.dequeueReusableCell(withIdentifier: secondCustomcellID, for: indexPath) as! AnotherCustomCell
    cell.rowContent.text = items[indexPath.row]
    cell.tableViewController = self
    return cell
    }

}

Upvotes: 1

Related Questions