Add and delete rows in UITableView Swift

In this post, we’ll discuss the scenario where we need to add or remove rows from a UITableView in Swift. Below are the parts of code required in the ViewController to achieve this.

First, we need to create the Outlet for the UITableView:

class NewRecipeVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

// don't forget to hook this up from the storyboard
@IBOutlet weak var newRecipeTableView: UITableView!

//hook this to the textbox to add the ingredient
@IBOutlet weak var ingredientTxt: UITextField!

//This array holds the ingredients
var ingredients = ["1 slice lemon","1 table spoon Sugar","1 glass Water","1 spoon Rock Salt"]

//hook this to a button
@IBAction func addIngredient(_ sender: Any) {
        if ingredientTxt.text != "" {
            ingredients.append(ingredientTxt.text!)
        
            let indexPath = IndexPath(row: ingredients.count - 1, section: 0)
            newRecipeTableView.beginUpdates()
            newRecipeTableView.insertRows(at: [indexPath], with: .automatic)
            newRecipeTableView.endUpdates()
        
            ingredientTxt.text = ""
            view.endEditing(true)

        }
        else {
            let alert = UIAlertController(title: "Missing!", message: "Missing ingredient...", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }

}

Deleting a row requires the commit editing style method as shown below. This method allows you to right to left swipe on the row and get the delete button option.

extension NewRecipeVC {    

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        if editingStyle == .delete {
            ingredients.remove(at: indexPath.row)
            newRecipeTableView.beginUpdates()
            newRecipeTableView.deleteRows(at: [indexPath], with: .automatic)
            newRecipeTableView.endUpdates()
        }
    }

}

Below are some methods that are used and are defined as per Apple documentation:

beginUpdates(): Begins a series of method calls that insert, delete, or select rows and sections of the table view.

insertRows(): Inserts rows in the table view at the locations identified by an array of index paths, with an option to animate the insertion.

deleteRows(): Deletes the rows specified by an array of index paths, with an option to animate the deletion.

endUpdates(): Concludes a series of method calls that insert, delete, select, or reload rows and sections of the table view.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.