This seems like a problem that should be common enough that it would have a good answer online, but I've had the hardest time finding one.
Essentially, my problem is this: I have a UITableView
in a ViewController
, and this table has MultipleSelection
enabled. Initially, if I "checked" (i.e., selected) cells and then scrolled till they were off screen, the check mark was gone when I scrolled back up. I was able to fix this first problem with answers I found online, but now I have a new problem that must be related to the way that UITableView
reuses cells: when I select cells, they inappropriately also select cells that are off-screen.
In viewDidLoad
:
self.friendListTableView.allowsMultipleSelection = true
And I implemented these two functions:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
Some places online said that one should store a separate data structure that keeps track of whether or not a cell is selected, but then other people said this should be automatically taken care of. Not sure what to believe.
I'm pretty sure the problem here is that when I do tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
, the checkmark is set for the on-screen index, not the actual index relative to the entire list. Any idea how to fix this? Thanks in advance.
EDIT: As requested, here's my cellForRowAtIndexPath
function...although it doesn't really do anything with regard to selected a cell....maybe it should.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if self.friendRecords[0].count == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: NO_FRIENDS, for: indexPath)
return cell
}
let friend = self.friendRecords[indexPath.section][indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: FRIEND_CELL, for: indexPath)
if let friendCell = cell as? FriendTableViewCell {
friendCell.username.text = (friend.object(forKey: USERNAME) as! String)
if friend.object(forKey: REAL_NAME) == nil {
friendCell.name.isHidden = true
}
else {
friendCell.name.text = (friend.object(forKey: REAL_NAME) as! String)
}
if friend.object(forKey: PROFILE_PIC) == nil {
friendCell.profilePic.image = UIImage(named: DEFAULT_PROFILE_PIC)
}
else {
let img = friend.object(forKey: PROFILE_PIC) as! CKAsset
friendCell.profilePic.image = UIImage(contentsOfFile: img.fileURL.path)
}
}
return cell
}