Mike Mike - 7 months ago 16
Swift Question

Delete a row in a section, please help find mistakes of my codes

I need to delete a row in a section but it deletes the row in upper section. Please help find problems of my codes. Also, please advise how to delete the section when deleting the row? There is one row in a section. Thanks.

var sectionTitles = [String]()
var savedURLs = [[String]]()

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return savedURLs.count
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return savedURLs[section].count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SavingCell")
cell?.textLabel!.text = savedURLs[indexPath.section][indexPath.row]
return cell!
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
savedURLs[indexPath.section].removeAtIndex(indexPath.row)
NSUserDefaults.standardUserDefaults().setObject(savedURLs, forKey: Key_SavedURLs)
savingTableView.reloadData()
}
}

Answer

To delete empty sections modify your code to this:

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

    if editingStyle == UITableViewCellEditingStyle.Delete {

        savedURLs[indexPath.section].removeAtIndex(indexPath.row)

        // now check if a section is empty and, if so, delete it

        if savedURLs[indexPath.section].count == 0 {
            savedURLs.removeAtIndex(indexPath.section)
        }

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

        savingTableView.reloadData()
    }
}

although for this to work your savedURLs should be [[String]]