Swipe-able Table View Cell in iOS 9

Dave G picture Dave G · Aug 14, 2015 · Viewed 77.3k times · Source

I want my table list to have a swipe-able menu like in iOS 8 (first introduced in iOS 7).

Screenshot of table view cell action buttons

I've found a Ray Wenderlich guide that is clear on how to do it, but it was written a year and 4 months ago and the code is in Objective-C.

Did iOS 8 or the upcoming iOS 9 finally include this function in Apple's SDK? I know they made the "swipe to reveal delete function" built-in years ago. I don't want to waste my time implementing patched-together code to mimic the iOS 8 mail function, if Apple's new iOS is going to hand it to me in a neatly wrapped package.

Answer

jose920405 picture jose920405 · Sep 15, 2015

Try this. (Updated for Swift 3.0) (Developer Docs)

override func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
    let more = UITableViewRowAction(style: .normal, title: "More") { action, index in
        print("more button tapped")
    }
    more.backgroundColor = .lightGray

    let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { action, index in
        print("favorite button tapped")
    }
    favorite.backgroundColor = .orange

    let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
        print("share button tapped")
    }
    share.backgroundColor = .blue

    return [share, favorite, more]
}

Also implement this: (You can make it conditional, but here everything is editable)

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

(Older Version)

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
        let more = UITableViewRowAction(style: .Normal, title: "More") { action, index in
            print("more button tapped")
        }
        more.backgroundColor = UIColor.lightGrayColor()

        let favorite = UITableViewRowAction(style: .Normal, title: "Favorite") { action, index in
            print("favorite button tapped")
        }
        favorite.backgroundColor = UIColor.orangeColor()

        let share = UITableViewRowAction(style: .Normal, title: "Share") { action, index in
            print("share button tapped")
        }
        share.backgroundColor = UIColor.blueColor()

        return [share, favorite, more]
    }

    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // the cells you would like the actions to appear needs to be editable
        return true
    }