Search code examples
iosswiftuitableviewuiactionsheet

Highlight tableview cell when tapped and unhighlight when alert controller action buttons are pressed


I like to highlight row in tableview cell when user touches the cell in blue, and then when user selects the action button, I want it to change it to gray color

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    var newCell = tableView.cellForRow(at: indexPath)!
    newCell.backgroundColor = UIColor.blue

    let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

    let okButton = UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in
        print("Ok button tapped")
        var newCell = tableView.cellForRow(at: indexPath)!
        newCell.backgroundColor = UIColor.gray
    })

    let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
        print("Cancel button tapped")
        var newCell = tableView.cellForRow(at: indexPath)!
        newCell.backgroundColor = UIColor.gray
    })

    alertController.addAction(okButton)
    alertController.addAction(cancelButton)

    present(alertController, animated: true, completion: nil)
}

func tableView(_ tableView: UITableView, didhighlightRowAt indexPath: IndexPath) {
    var newCell = tableView.cellForRow(at: indexPath)!
    newCell.backgroundColor = UIColor.clear
}

I did this and it highlights the cell in white color and after action button is tapped, it still stays white but when I tap another cell, the previous cell turns and remains gray


Solution

  • In view controller initialization:

    NSMutableSet *selectedRows = NSMutableSet.alloc.init;
    NSIndexPath *lastSelected = nil;
    

    In table view initialization: tableview.allowsMultipleSelection = false

    In did select row: Fire alert (you already have this), lastSelected = indexPath;, [selectedRows addObject:indexPath.row].

    In cell for row: cell.selectionStyle = UITableViewSelectionStyleBlue;

    if ([selectionSet contains:indexPath.row])
        cell.backgroundColor = UIColor.grayColor;
    else
        cell.backgroundColor = UIColor.clearColor;
    

    In alert view delegate: [tableview deselectRowAtIndexPath:selectedIndexPath] and [tableview reloadIndexPath:lastSelection]

    This should: 1) start with all cells clear

    2) turn cell blue when clicked by default highlighting

    3) redraw cell after alert view selection

    4) cell will redraw with gray color if it is in the selectedRow set