Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView editActionsForRowAtIndexPath stops working if you return an empty array

I have a UITableView for which I have added some custom slide out buttons. These all work as expected. There is however a scenario in my table where a row can be in a state where none of the slide out buttons are relevant and so I have been returning an empty array of actions so the slide out buttons wont appear. Unfortunately once this occurs the UITableView stops calling my editActionsForRowAtIndexPath effectively disabling slide out buttons for all rows in my table ... and it seems permanent until the app is restarted.

Is this expected behaviour?

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]?
{
    if mydata[indexPath.row].EditAvailable()
    {
        var editAction = UITableViewRowAction(style: .Default, title: "Edit", handler: editHandler)
        return [editAction]
    }
    else
    { 
        return []
    }
}
like image 766
Keith westley Avatar asked Jan 12 '15 10:01

Keith westley


2 Answers

The way I solved this problem was to implement the function,

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool

Here, you should just return false if you don't want the expected row to have the swipe feature.

So you code would look something like this

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
  return mydata[indexPath.row].EditAvailable()
}

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]?
{
  var editAction = UITableViewRowAction(style: .Default, title: "Edit", handler: editHandler)
  return [editAction]
}

The editActionsForRowAtIndexPath is then only called for the ones that you indicated are editable.

like image 199
fstef Avatar answered Mar 01 '23 22:03

fstef


First, editActionsForRowAtIndexPath should return nil and not [] when then are no actions.

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]?
{
    if mydata[indexPath.row].EditAvailable()
    {
        var editAction = UITableViewRowAction(style: .Default, title: "Edit", handler: editHandler)
        return [editAction]
    }
    else
    { 
        return nil
    }
}

Second, you must implement editingStyleForRowAtIndexPath to disable the default "Delete" action for the other rows.

func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
    if mydata[indexPath.row].EditAvailable() {
        return UITableViewCellEditingStyle.Delete
    }
    return UITableViewCellEditingStyle.None
}

Thanks luciano for the tip empty array/nil tip

like image 28
litso Avatar answered Mar 02 '23 00:03

litso