First, I want to build my app like this image.
This app has a table view.
A table view has several sections.
Each Section
has different number of cells.
Each Cell
has different types of accessories as sub-view.
Because of this concept, this table view reuses different UITableViewCell
sub-classes for each cells.
And I want to let users customize a table view by saving after selecting buttons which indicates the cells
.
Here's the first step : TableViewController
code. It works well as I intended.
class TableViewController: UITableViewController {
let foodComponents = [["Apple", "Banana", "Grape", "Pear"], ["Beef", "Pork", "Chicken"], ["Shrimp", "Cod", "Anchovy"]]
let headerTitles = ["Fruits", "Meats", "Fishes"]
let cellReuseidentifier = "cell"
let anotherCellReuseidentifier = "anotherCell"
// + other identifiers for UITableViewCell subclasses
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(FruitTableViewCell.self, forCellReuseIdentifier: cellReuseidentifier)
tableView.register(AnotherFruitTableViewCell.self, forCellReuseIdentifier: anotherCellReuseidentifier)
// + other UITableViewCell subclasses
}
override func numberOfSections(in tableView: UITableView) -> Int {
return foodComponents.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return foodComponents.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseidentifier, for: indexPath) as! FruitTableViewCell
cell.textLabel?.text = foodComponents[indexPath.row]
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: anotherCellReuseidentifier, for: indexPath) as! AnotherFruitTableViewCell
cell.textLabel?.text = foodComponents[indexPath.row]
return cell
}
}
// an so on...
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section < headerTitles.count {
return headerTitles[section]
}
return nil
}
}
The second step is making another view which contains many UIButton
s to let users customize themselves by selecting them.
But the problem is,
1. Getting user-selected values into the array in the TableViewController
2. Identifying them which the TableViewCell subclass belongs to them.
The Array
in the TableViewController
is the basis for numberOfSections
, numberOfRows
, cellForRow
.
But if users select cells, it means that the array will be changed.
If the array is not fixed, numberOfSections
, numberOfRows
, cellForRow
functions will not be executed. And, if TableViewCell
subclass for user-selected value is not identified, the cells cannot be made.
How to get and identify data from other view into the array in UITableViewController
?