I have a table view and I would like the user to select only one item from the table view, then I want to add a checkmark to the cell. At the same time, I also want the checkmark on other cells to disappear so the. user can only select one at a time. Then I want to save the data (preferably using UserDefaults
). How do I do that?
Asked
Active
Viewed 870 times
0

techcoderx
- 602
- 1
- 7
- 21
2 Answers
1
Create a class variable of type IndexPath. In your cellForRowAt method set .checkmark accessory type only if index path matches the class variable and .none otherwise. In didSelectRowAt method update the indexPath of selected variable and just reload the tableview

Bharath Reddy
- 636
- 1
- 5
- 21
-
I got this error, screenshot of code and debugger output here: https://www.dropbox.com/s/jlqucl40piso7e5/save%20checkmark%20accessory.png?dl=0 – techcoderx Mar 18 '17 at 07:11
-
You need not save indexPath in user defaults...you can simply create a class variable. In the screen shot you are storing index path in the user defaults...What data do you want to save in user defaults? – Bharath Reddy Mar 18 '17 at 08:00
-
I want to save the index path for the selected row so that when I refresh the table view I can get the indexpath from user defaults and set the accessory checkmark based on that indexpath – techcoderx Mar 18 '17 at 08:14
-
Instead of saving index path directly. Save index path.row as int in user defaults and get that int, construct index path from it..You can't save index path type directly into user defaults – Bharath Reddy Mar 18 '17 at 08:43
0
you should Use in this way
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let sgp : UITableViewCell = tableView.cellForRow(at: indexPath)!
sgp.accessoryType = .checkmark
}

Sagar vaishnav
- 97
- 1
- 1
- 7