Mike Mike - 7 months ago 22
Swift Question

How to delete a row in a section?

My TableView contains multiple sections. Now when I click "delete" for the row selected, it deleted the row in upper section. How to fix this?

I guess the Index for the row to delete in not correct, but I am not sure and have no idea how to fix it. This is my code:

var sectionTitles = [String]()

var savedURLs = [[String]]()

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

if editingStyle == UITableViewCellEditingStyle.Delete {

savedURLs.removeAtIndex(indexPath.row)

NSUserDefaults.standardUserDefaults().setObject(savedURLs, forKey: Key_SavedURLs)

savingTableView.reloadData()
}
}

Answer

NSIndexPath identifies both the row as well as the section of the cell. You need to check the indexPath.section and the indexPath.row to know which item in your savedURLs was deleted.

Comments