Reputation: 2025
I have an application where I used table view with custom cells which works fine. The problem I am having now is I want to make it dynamic by this, the number of cell is not fixed. That is, the cell could be 1, 2, 3 or 5, depending on the count of an array. This cell UI varies, too
Cell1: could have an image and a label.
Cell2: could have two labels.
Cell3: could have a dayPicker.
this is the way to create the cells when I know the number returned
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "firstTableCell") as! FirstTableCell
// Set up cell.label
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "secondTableCell") as! SecondTableCell
// Set up cell.button
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "thirdTableCell") as! ThirdTableCell
// Set up cell.textField
return cell
}
}
but now numberOfRowsInSection
varies and so those the view items.
how can I do this? Programmatically or otherwise, programmatically preferred.
Upvotes: 0
Views: 250
Reputation: 285082
A dynamic table view can be accomplished with an appropriate data model.
For example use an enum for the kind and a struct with a member to indicate the kind
enum CellKind {
case image, label, picker
}
struct Model {
let kind : CellKind
// other struct members
}
How many cells are displayed depends on the items in the data source array
var items = [Model]()
In numberOfRows
return the number of items
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
In cellForRow
display the cells depending on the kind rather than on the index path
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.row]
switch item.kind {
case .image:
let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! ImageCell
// Set up cell.image
return cell
case .label:
let cell = tableView.dequeueReusableCell(withIdentifier: "labelCell") as! LabelCell
// Set up cell.label
return cell
case .picker:
let cell = tableView.dequeueReusableCell(withIdentifier: "pickerCell") as! PickerCell
// Set up cell.picker
return cell
}
}
Upvotes: 5