I'm using a UITableView, with 3 sections ( Static Cells )
They have different number of rows:
Right now, I have by default set a checkmark at the first row of every section. However, I would like to allow the user to set their default settings and change the checkmark accordingly based on what they have set.
My question is then how do I set the checkmark for 3 different sections each with varying number of rows?
Do I need to set an cell identifier for each Section? Do I also need to create a UITableViewCell swift file for each Section?
If the checkmarks are set in response to tapping on the cell, just implement tableView(_:didSelectRowAtIndexPath:)
:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = indexPath.section
let numberOfRows = tableView.numberOfRowsInSection(section)
for row in 0..<numberOfRows {
if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) {
cell.accessoryType = row == indexPath.row ? .Checkmark : .None
}
}
// ... update the model ...
}
Otherwise, you can set identifiers for each cell in your storyboard (or outlets if you prefer, since the cells aren't reused), and then just set the checkmark programmatically. For example, using a delegate method:
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let identifier = cell.reuseIdentifier {
switch identifier {
"USD Cell": cell.accessoryType = model.usdChecked ? .Checkmark : .None
"EUR Cell": cell.accessoryType = model.eurChecked ? .Checkmark : .None
//...
default: break
}
}
}
There shouldn't be a need to create a separate subclass for each section/cell.
Just a quick update for Swift 3:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let section = indexPath.section
let numberOfRows = tableView.numberOfRows(inSection: section)
for row in 0..<numberOfRows {
if let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) {
cell.accessoryType = row == indexPath.row ? .checkmark : .none
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With