[英]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.我试过把它放在我代码的各个部分,比如在 commitEditingStyle 方法的末尾,但我无法让它停止编辑模式。 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];
}
How about [self setEditing:NO animated:YES]
? [self setEditing:NO animated:YES]
怎么样? I suppose to self is an instance of UITableViewController.我想 self 是 UITableViewController 的一个实例。
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.因此,在
commitEditingStyle
调用它并不是一个好习惯。
如果不只是[self setEditing:NO animated:YES]
?
After playing around with this, here are the things to know: There are separate setEditing routines for the controller and for the tableView.在玩弄这个之后,这里是需要知道的事情: 控制器和 tableView 有单独的 setEditing 例程。 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 .
为此,我使用了Matt 的延迟功能。 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.
代码在 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)
}
}
Swift 5 等效项:
super.setEditing(false, animated: true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.