GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

How to customize swipe edit buttons in a UITableView

Swift version: 5.10

Paul Hudson    @twostraws   

As of iOS 8.0 there's an easy way to customize the list of buttons that appear when the user swipes from right to left: editActionsForRowAt. Return an array of UITableViewRowAction objects that have titles and styles (and also background colors if you want to customize their appearance), and iOS does the rest.

When you create a UITableViewRowAction object you give it a trailing closure describing what should happen when the user taps the button. You'll get reminded of what action triggered the code, and you'll also be given the index path of the row where the user was tapping. For example, you might do this:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in
        // delete item at indexPath
    }

    let share = UITableViewRowAction(style: .normal, title: "Disable") { (action, indexPath) in
        // share item at indexPath
    }

    share.backgroundColor = UIColor.blue

    return [delete, share]
}

Note that the first button uses a .destructive style so it will be colored red by default, but the second button specifically has a blue color assigned to it.

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 8.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.3/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.