Bhagabata
Bhagabata

Reputation: 473

How to delete specific rows in a table view cell?

I am using a table view which consists of three sections. User can delete the rows for third section. But while I am using table view delegate method for deleting rows ,It is affecting for other sections. So how could I overcome from this problem?

Here is my code

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
      numbers.removeAtIndex(indexPath.row)    
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }

Upvotes: 1

Views: 3271

Answers (3)

vadian
vadian

Reputation: 285082

If you want to restrict editing to section 2 implement canEditRowAt (code is Swift 3+)

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return indexPath.section == 2
}

Or add a check

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete && indexPath.section == 2 {
      numbers.remove(at: indexPath.row)    
      tableView.deleteRows(at: [indexPath], with: .automatic)
    }

Upvotes: 4

this.girish
this.girish

Reputation: 1306

correct way of doing this is

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return indexPath.section == 2
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
   if editingStyle == .delete && indexPath.section == 2
   {
      yourArray.remove(at: indexPath.row)
      yourtable.reloadData()
   }
}

Upvotes: 0

Vlad Pulichev
Vlad Pulichev

Reputation: 3272

In function with forRowAt indexPath: IndexPath you have IndexPath value.

It contains .section. So, you can simply check, which section have you selected and then do or not do deleting.

To delete rows for specific section:

tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

Hope it helps

Upvotes: 0

Related Questions