Reputation: 33
I'm trying to show checkmark on tableview cell, but the checkmark appears only sometimes and it disappears when I scroll.
Below the code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("vvxxx12", forIndexPath: indexPath)
// Configure the cell...
cell.textLabel?.text = self.dataArray[indexPath.row] as? String //in dataArray values are stored
if dataArray.containsObject(indexPath)
{
cell.accessoryType = .Checkmark
}
else {
cell.accessoryType = .None
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.accessoryType == .Checkmark {
cell.accessoryType = .None
} else {
cell.accessoryType = .Checkmark
}
}
}
Upvotes: 1
Views: 9404
Reputation: 475
For Swift 3 following worked for me to
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
yourtableView.cellForRow(at: indexPath as IndexPath)?.accessoryType = .checkmark
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
yourtableView.cellForRow(at: indexPath as IndexPath)?.accessoryType = .none
}
Upvotes: 1
Reputation: 1749
Just do following changes in your code to maintain checkmark into tableview while you are scrolling tableview
Result :
Its work fine now, Any problem let me know i will definitely help you to out.Enjoy..
Upvotes: 2
Reputation: 119292
cell.textLabel?.text = self.dataArray[indexPath.row] as? String
This suggests that dataArray
contains strings.
if dataArray.containsObject(indexPath)
This suggests that dataArray
contains index paths. Both of these should not be true. One array for data makes sense, and another one for selected rows or rows to be checked also makes sense, but not the same array for both.
What's probably happening is:
dataArray
contain an index path, so the accessory is always cleared.You need to be updating your model when a row is selected, to store the index path of the selected row, or update a selected flag on your model objects.
Upvotes: 0