iOS Swift UITableViewCell custom swipe action buttons example

iOS Swift UITableViewCell custom swipe action buttons example
To add custom actions to your table view's rows, implement the tableView(_:editActionsForRowAt:) method in your table view's delegate object. Users swipe horizontally in a table view to reveal the actions associated with a row. Each row-action object contains the text display, the action to perform, and any specific formatting to apply to that action. If you do not implement this method, the table view displays the standard accessory buttons when the user swipes the row.


    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath)
        -> [UITableViewRowAction]? {
        
        let delete = UITableViewRowAction(style: .destructive, title: "Delete",
                                          handler: handleRowAction)
        let edit = UITableViewRowAction(style: .normal, title: "Edit",
                                        handler: handleRowAction)
        edit.backgroundColor = UIColor.blue
        let other = UITableViewRowAction(style: .normal, title: "Other",
                                         handler: handleRowAction)
        other.backgroundColor = UIColor.orange
        return [other, edit, delete]
        
    }


Complete Source for UIViewController


import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    //my sample data for table view
    private var myArray: [String] = [
        "This is Row# 1",
        "This is Row# 2",
        "This is Row# 3",
        "This is Row# 4"]
    private var myTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "Main View"
        
        myTableView = UITableView()
        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
        myTableView.dataSource = self
        myTableView.delegate = self
        myTableView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(myTableView)
        
        //hide empty rows at the bottom
        myTableView.tableFooterView = UIView()
        
        //auto layout for the table view
        let views = ["view": view!, "tableView" : myTableView]
        var allConstraints: [NSLayoutConstraint] = []
        allConstraints += NSLayoutConstraint.constraints(withVisualFormat:
            "V:|[tableView]|", options: [], metrics: nil, views: views as [String : Any])
        allConstraints += NSLayoutConstraint.constraints(withVisualFormat:
            "H:|[tableView]|", options: [], metrics: nil, views: views as [String : Any])
        NSLayoutConstraint.activate(allConstraints)
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Num: \(indexPath.row)")
        print("Value: \(myArray[indexPath.row])")
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)
        -> Int {
            return myArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
        -> UITableViewCell {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell",
                                                     for: indexPath as IndexPath)
            cell.textLabel!.text = "\(myArray[indexPath.row])"
            return cell
    }
    
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath)
        -> [UITableViewRowAction]? {
        
        let delete = UITableViewRowAction(style: .destructive, title: "Delete",
                                          handler: handleRowAction)
        let edit = UITableViewRowAction(style: .normal, title: "Edit",
                                        handler: handleRowAction)
        edit.backgroundColor = UIColor.blue
        let other = UITableViewRowAction(style: .normal, title: "Other",
                                         handler: handleRowAction)
        other.backgroundColor = UIColor.orange
        return [other, edit, delete]
        
    }
    
    func handleRowAction(action: UITableViewRowAction, indexPath: IndexPath){
        print("Action is \(action.title!) at Index Path \(indexPath)")
        
        let actionItem = action.title
        switch actionItem {
            
        case "Delete":
            myArray.remove(at: indexPath.row)
            myTableView.deleteRows(at: [indexPath as IndexPath], with: .fade)
            
        case "Edit":
            let alert = UIAlertController(title: "Edit Row Entry",
                                          message: nil,
                                          preferredStyle: .alert)
            
            alert.addTextField { (textField: UITextField) in
                textField.keyboardAppearance = .dark
                textField.keyboardType = .default
                textField.autocorrectionType = .default
                textField.placeholder = self.myArray[indexPath.row]
            }
            
            alert.addAction(UIAlertAction(title: "Save", style: .default, handler: { action in
                self.myArray[indexPath.row] = alert.textFields![0].text!
                self.myTableView.reloadRows(at: [indexPath], with: .top)
            }))
            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
                print("Edit Cancelled...")}))
            
            self.present(alert, animated: true)
            
        case "Other":
            print("Any Other Action!")
            
        default:
            print("Default just in case")
        }
        
    }
    
    
}


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.