07-21-2023, 07:54 PM
The above answers that hide/show cells, change rowHeight, or mess with Auto layout constraints didn't work for me because of Auto layout issues. The code became intolerable.
For a simple static table, what worked best for me was to:
1. Create an outlet for every cell in the static table
2. Create an array only with the outlets of cells to show
3. Override cellForRowAtIndexPath to return the cell from the array
4. Override numberOfRowsInSection to return the count of the array
5. Implement a method to determine what cells need to be in that array, and call that method whenever needed, and then reloadData.
Here is an example from my table view controller:
@IBOutlet weak var titleCell: UITableViewCell!
@IBOutlet weak var nagCell: UITableViewCell!
@IBOutlet weak var categoryCell: UITableViewCell!
var cellsToShow: [UITableViewCell] = []
override func viewDidLoad() {
super.viewDidLoad()
determinCellsToShow()
}
func determinCellsToShow() {
if detail!.duration.type != nil {
cellsToShow = [titleCell, nagCell, categoryCell]
}
else {
cellsToShow = [titleCell, categoryCell]
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return cellsToShow[indexPath.row]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellsToShow.count
}
For a simple static table, what worked best for me was to:
1. Create an outlet for every cell in the static table
2. Create an array only with the outlets of cells to show
3. Override cellForRowAtIndexPath to return the cell from the array
4. Override numberOfRowsInSection to return the count of the array
5. Implement a method to determine what cells need to be in that array, and call that method whenever needed, and then reloadData.
Here is an example from my table view controller:
@IBOutlet weak var titleCell: UITableViewCell!
@IBOutlet weak var nagCell: UITableViewCell!
@IBOutlet weak var categoryCell: UITableViewCell!
var cellsToShow: [UITableViewCell] = []
override func viewDidLoad() {
super.viewDidLoad()
determinCellsToShow()
}
func determinCellsToShow() {
if detail!.duration.type != nil {
cellsToShow = [titleCell, nagCell, categoryCell]
}
else {
cellsToShow = [titleCell, categoryCell]
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return cellsToShow[indexPath.row]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellsToShow.count
}