Create swipe-able cells in about 5 minutes with Swift

The iOS SDK enables the developer to rapid prototype ideas without writing boiler plate code for hours. One example of this is the possibility to add swipe-able cells to your UITableView. This feature is heavily used in the iOS Mail App. It took me between five and ten minutes to implement the first version of my cells.

At first, we have to go to the UITableViewDelegate implementation of our tableview controller. We have to add a method stub that enables the „swipeness“. For detail information and inheritance tree, please have a look at the Apple Developer reference article.

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        // Required for the following methods
}

After this, we override a method that adds the required acion buttons to the cell in case of a detected swipe gesture.

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]?  {
    var action1 = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Action 1" , handler: {
        (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
            // Do what ever you want.

            // Auto. swipe back to default state
            // The 'self' prefix is required due to the capitulating closure
            self.tableView.editing = false
        })
        // Change color if you want.
        subscribeAction.backgroundColor = UIColor.grayColor()

        var action2 = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Action 2" , handler: {
            (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
            // Again, do what you have to do. :)

            // Auto. swipe back to default state
            // The 'self' prefix is required due to the capitulating closure
            self.tableView.editing = false
        })

        return [action1, action2]
 }

This code is used to implement Nomster’s swipe-able cell feature. Have a look at the ListViewcontroller class in Nomster’s Github repository.

Nomster swipe-able cell

For a deeper look, I recommend Ray Wenderlich’s article ‚How To Make A Swipeable Table View Cell With Actions – Without Going Nuts With Scroll Views‘.

Schreibe einen Kommentar

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s