Deleting Rows

In editing mode, the red circles with the minus sign (shown in Figure 11.7) are deletion controls, and tapping one should delete that row. However, at this point, you cannot actually delete the row. (Try it and see.) Before the table view will delete a row, it calls a method on its data source about the proposed deletion and waits for confirmation.

When deleting a cell, you must do two things: remove the row from the UITableView and remove the Item associated with it from the ItemStore. To pull this off, the ItemStore must know how to remove objects from itself.

In ItemStore.swift, implement a new method to remove a specific item.

func removeItem(_ item: Item) {
    if let index = allItems.index(of: item) {
        allItems.remove(at: index)
    }
}

Now you will implement tableView(_:commit:forRow:), a method from the UITableViewDataSource protocol. (This method is called on the ItemsViewController. Keep in mind that while the ItemStore is where the data is kept, the ItemsViewController is the table view’s dataSource.)

When tableView(_:commit:forRowAt:) is called on the data source, two extra arguments are passed along with it. The first is the UITableViewCellEditingStyle, which, in this case, is .delete. The other argument is the IndexPath of the row in the table.

In ItemsViewController.swift, implement this method to have the ItemStore remove the right object and confirm the row deletion by calling the method deleteRows(at:with:) on the table view.

override func tableView(_ tableView: UITableView,
                        commit editingStyle: UITableViewCellEditingStyle,
                        forRowAt indexPath: IndexPath) {
    // If the table view is asking to commit a delete command...
    if editingStyle == .delete {
        let item = itemStore.allItems[indexPath.row]
        // Remove the item from the store
        itemStore.removeItem(item)

        // Also remove that row from the table view with an animation
        tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

Build and run your application, create some rows, and then delete a row. It will disappear. Notice that swipe-to-delete works also.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset