0

I'm implementing a UITableViewController in my app and I want to add a possibility of sliding/swiping a cell on my tableview, exactly like in this answer: Swipe-able Table View Cell in iOS 9 but with a difference that it works only for one specific cell, not all of them. So far I have:

class MyTableViewController: UITableViewController {



override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

override func tableView(tableView: (UITableView!), commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: (NSIndexPath!)) {

}

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

    var deleteAction = UITableViewRowAction(style: .Default, title: "Hello There!") {action in
        print("some action!!")
    }

    return [deleteAction]
}

}

and it adds the swiping for all cells and I want to add it only to the 3rd one on my list (cells are not generated dynamically). Is there a way of doing that?

Community
  • 1
  • 1
randomuser1
  • 2,733
  • 6
  • 32
  • 68

1 Answers1

3

You can check the indexPath of the cell which is given as parameter and return the appropriate response based on that. Furthermore, you could also check the type of your cell using func cellForRowAtIndexPath(_ indexPath: NSIndexPath) -> UITableViewCell? if you have different cells or so.

Index path is a class. You can get the index of the current row from the indexPath using indexPath.row.

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    if ((indexPath.row % 3) == 0) {
       return true
    } else {
       return false
    }
 }
Jelly
  • 4,522
  • 6
  • 26
  • 42
  • but is the `indexPath` an int that I can compare to number 3? or how exactly could I do it in this case? – randomuser1 Mar 30 '16 at 18:50
  • 1
    You can compare `indexPath.row` to 3 – dan Mar 30 '16 at 18:53
  • Ok, so I did: `if (indexPath.row == 2) { var deleteAction = UITableViewRowAction(... } else { return nil }` but still it's possible to slide every cell. With that solution in my 3rd cell I see the string `Hello There!` and when I slide the other ones I see the string `Delete`. Is there a way of completely removing the possibility of sliding the other cells then? :) – randomuser1 Mar 30 '16 at 18:57
  • Thank you Jelly :) – randomuser1 Mar 30 '16 at 19:04