Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn off editing mode in UITableView when there are no more cells to delete?

I've tried putting this in various parts of my code, like at the end of commitEditingStyle method, but I can't get it to stop editing mode. Basically, I want to automatically exit editing mode when there are no more cells...

if ([self.tableView numberOfRowsInSection:0] ==0)
    {
        NSLog(@"this triggers, but doesn't stop editing..");
        self.tableView.editing = NO;
        [self.tableView endEditing:YES];
    }
like image 707
cannyboy Avatar asked Nov 24 '10 12:11

cannyboy


4 Answers

How about [self setEditing:NO animated:YES]? I suppose to self is an instance of UITableViewController.

like image 96
AechoLiu Avatar answered Oct 14 '22 04:10

AechoLiu


From the apple docs:

Note: The data source should not call setEditing:animated: from within its implementation of tableView:commitEditingStyle:forRowAtIndexPath:. If for some reason it must, it should invoke it after a delay by using the performSelector:withObject:afterDelay: method.

So, calling this within commitEditingStyle is not a great practice.

like image 32
tooluser Avatar answered Oct 14 '22 04:10

tooluser


If is not just [self setEditing:NO animated:YES] ?

like image 32
Benoît Avatar answered Oct 14 '22 02:10

Benoît


After playing around with this, here are the things to know: There are separate setEditing routines for the controller and for the tableView. Make sure to use the one for the controller. Also, it needs a delay as noted above. For this, I used Matt’s delay function. As an added bonus, one can disable the Edit button when there are no items in your list. The button becomes enabled again when an item is added. Code is in Swift5.

var someArray: [SomeStruct] = [] {
    didSet {
        if let btn = navigationItem.rightBarButtonItem {
            if someArray.count > 0 {
                btn.isEnabled = true
            } else {
                btn.isEnabled = false   // Needs to respond immediately - don't put in delay
                closeDownEditMode()
            }
        }
    }
}

func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

func closeDownEditMode() {
    delay(0.1) { [weak self] in
        self?.setEditing(false, animated: true)
    }
}
like image 38
anorskdev Avatar answered Oct 14 '22 04:10

anorskdev