Skip to content

Instantly share code, notes, and snippets.

@RNHTTR
Created September 23, 2017 20:14
Show Gist options
  • Save RNHTTR/8709c787eec8815f25d14879e390dfdf to your computer and use it in GitHub Desktop.
Save RNHTTR/8709c787eec8815f25d14879e390dfdf to your computer and use it in GitHub Desktop.
Use tableView(_:editActionsForRowAt:) to implement swipe actions for a UITableView's cells.
// Use tableView(_:editActionsForRowAt:) to implement swipe actions for a UITableView's cells.
// This example exhibits how this app makes use of this method.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// Get the title of each section to notify the user that a cell in a particular section was swiped.
let sectionHeaderView = tableView.headerView(forSection: indexPath.section)
let sectionTitle = sectionHeaderView?.textLabel?.text
// Create an action. Create custom actions in the UITableViewRowAction's closure.
let firstBox = UITableViewRowAction(style: .normal, title: "First") { action, index in
// Create an alert to notify users when they horizontally swiped a cell and then selected the first action.
let alert = UIAlertController(title: "Alert", message: "You tapped the \"First\" box from the \(sectionTitle!) section.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
// Set the background color of the first action.
firstBox.backgroundColor = UIColor.green
// Create another action and customize the actions in the UITableViewRowAction's closure.
let secondBox = UITableViewRowAction(style: .normal, title: "Second") { action, index in
// Create an alert to notify users when they horizontally swiped a cell and then selected the second action.
let alert = UIAlertController(title: "Alert", message: "You tapped the \"Second\" box from the \(sectionTitle!) section.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
// Set the background color of the second action.
secondBox.backgroundColor = UIColor.green.withAlphaComponent(0.5)
// Return the actions. Notice the order of the array. Actions are added from right to left.
return [secondBox, firstBox]
}
// Implement this function to allow editing for all cells.
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment