Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save StephenHeaps/3fac5bdbfe58974cd952ee5f5154a839 to your computer and use it in GitHub Desktop.
Save StephenHeaps/3fac5bdbfe58974cd952ee5f5154a839 to your computer and use it in GitHub Desktop.
iOS 11 added a nice easy way to add Custom Swipe-able Actions in UITableView using the UITableViewDelegate protocol
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let contextItem = UIContextualAction(style: .normal, title: "Leading & .normal") { (contextualAction, view, boolValue) in
print("Leading Action style .normal")
}
let swipeActions = UISwipeActionsConfiguration(actions: [contextItem])
return swipeActions
}
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let contextItem = UIContextualAction(style: .destructive, title: "Trailing & .destructive") { (contextualAction, view, boolValue) in
print("Trailing Action style .destructive")
}
let swipeActions = UISwipeActionsConfiguration(actions: [contextItem])
return swipeActions
}
@StephenHeaps
Copy link
Author

Two new methods in the UITableViewDelegate protocol are a nice addition.

Can simply copy/paste this into a Master Detail template app to demo.

@MainasuK
Copy link

MainasuK commented Jun 7, 2017

Thank you for your code snippet.

And UIContextualActionHandler defined like this:
typealias UIContextualActionHandler = (UIContextualAction, UIView, (Bool) -> Void) -> Void

So we can let swipe done by calling the bool function

    override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let contextual = UIContextualAction(style: .normal, title: "Leading") { (contextAction, view, isSuccess) in
            print("leading swipe action")

            isSuccess(true)
        }

        return UISwipeActionsConfiguration(actions: [contextual])
    }

@akultomar17
Copy link

For multiple UIContextualActions I'm facing an issue where titles and icons are misaligned, similar to this
https://stackoverflow.com/questions/48671607/uicontextualaction-icon-and-text-alignment

Any fix?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment