Mike
Mike

Reputation: 37

How to delete a row in a section with Swift?

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.

    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()
        }
    }

Upvotes: 1

Views: 2594

Answers (2)

Andriy Gordiychuk
Andriy Gordiychuk

Reputation: 6282

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]]

Upvotes: 2

fahad khan
fahad khan

Reputation: 89

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

    if editingStyle == UITableViewCellEditingStyle.Delete {
        savedURLs.removeAtIndex(indexPath.section)    
        NSUserDefaults.standardUserDefaults().setObject(savedURLs, forKey: Key_SavedURLs)

        savingTableView.reloadData()
    }
}

try this.this should work..

Upvotes: 1

Related Questions