Display two buttons when row is selected in tableview using swift 4

Robert Smith Source

Is there a way to display the UITableViewRowAction buttons when user selects the cell (as opposed to how UITableViewRowAction works by default which requires tableview to be in edit mode).

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?
        let shareAction  = UITableViewRowAction(style: .Normal, title: "Share") { (rowAction, indexPath) in
            print("Share Button tapped. Row item value = \(self.itemsToLoad[indexPath.row])")

        let deleteAction  = UITableViewRowAction(style: .Default, title: "Delete") { (rowAction, indexPath) in
            print("Delete Button tapped. Row item value = \(self.itemsToLoad[indexPath.row])")
        shareAction.backgroundColor = UIColor.greenColor()
        return [shareAction,deleteAction]


answered 7 months ago Duncan C #1

Its unlikely that you're going to find code in another answer that you can drop into your project and have it work, especially if that code was written in another language. You're going to modify YOUR code to do what you want.

In general, you should not manipulate your cells directly. You should set up your data model to contain the state information used to configure a cell. You might have an array of structs where each array entry describes the info to be displayed in a single cell. (If you use a sectioned table view you might use an array of arrays, where the outer array is your sections and each inner array contains structs for the rows in a section.)

Below is an outline of how you might implement this:

struct CellData {
   var title: String 
   var showButtons: Bool

Then in your tabView(_:didSelect:) method, set the showButtons flag on the previously selected indexPath (if any) to false, set the showButtons flag on the newly selected cell to true, and call reloadRows(at:with:) to re-draw the deselected cell and the newly selected cell.

If you allow multiple cells to be selected at a time then you would not clear the showButtons flag for the previously selected cells.

In your cellForRow(at:) method, use the showButtons flag to decide if your buttons should be hidden or not.

comments powered by Disqus