简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM