Created
November 4, 2019 11:29
-
-
Save dilipiOSDeveloper/635debb739ea839b271ebff36062421f to your computer and use it in GitHub Desktop.
Save the state of checkmarked cell in table view in swift 4.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
First of all rather than multiple arrays use a struct for the data source. | |
And don't use extra arrays or dictionaries to maintain the selection either, this is error-prone and unnecessarily expensive. | |
Add a boolean member to the struct for the selected state. | |
struct Course : Codable { | |
let name : String | |
let image : String | |
var isSelected : Bool | |
} | |
Declare the data source array | |
var courses = [Course(name: "Sound", image: "speaker", isSelected: false), | |
Course(name: "Vibrate", image: "Group 1094", isSelected: false), | |
Course(name: "Both", image: "Group 1093", isSelected: false), | |
Course(name: "None", image: "speaker-1", isSelected: false)] | |
First of all rather than multiple arrays use a struct for the data source. | |
And don't use extra arrays or dictionaries to maintain the selection either, this is error-prone and unnecessarily expensive. | |
Add a boolean member to the struct for the selected state. | |
struct Course : Codable { | |
let name : String | |
let image : String | |
var isSelected : Bool | |
} | |
Declare the data source array | |
var courses = [Course(name: "Sound", image: "speaker", isSelected: false), | |
Course(name: "Vibrate", image: "Group 1094", isSelected: false), | |
Course(name: "Both", image: "Group 1093", isSelected: false), | |
Course(name: "None", image: "speaker-1", isSelected: false)] | |
In cellForRowAt set the checkmark depending on isSelected | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! VibTableViewCell | |
let course = courses[indexPath.row] | |
cell.label.text = course.name | |
// define the text color in Interface Builder | |
// cell.label.textColor = UIColor.darkGray | |
cell.photo.image = UIImage(named: course.image) | |
cell.accessoryType = course.isSelected ? .checkmark : .none | |
return cell | |
} | |
In didSelectRowAt toggle the isSelected value in the data source and reload the row | |
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { | |
courses[indexPath.row].isSelected.toggle() | |
tableView.reloadRows(at: indexPath, with: .none) | |
} | |
Finally delete the method didDeselectRowAt | |
To save the array you could write | |
do { | |
let data = try JSONEncoder().encode(courses) | |
UserDefaults.standard.set(data, forKey: "Courses") | |
} ca |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment