从UITableView - Swift中删除行的正确方法是什么? [英] What is the proper way to delete rows from a UITableView - Swift

查看:151
本文介绍了从UITableView - Swift中删除行的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,我从tableView中删除一行时使用了以下代码,它运行正常。

In Objective-C I have used the following code when deleting a row from a tableView and it works just fine.

Objective-C示例

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.arrayName removeObjectAtIndex:indexPath.row];
    [self.tableName reloadData];
}

我最近搜索了一下如何在Swift中完成这项工作,我注意到了我发现的大多数代码都与我之前使用的代码不同。

I recently made a search to see how this was done in Swift and I noticed that most of the code I found is different than what I used before.

Swift示例

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

现在问题是,我做错了还是两种方式都没问题?

So now the question is, have I been doing it wrong or both ways are ok?

正确的方法是什么?在任何一种语言(Swift或Objective-C)?

What is the correct way in either language (Swift or Objective-C)?

推荐答案

Objective-C代码有效,但实际上并不是正确的方法。它应该与您发布的示例Swift代码类似。

The Objective-C code works but isn't really the proper way. It should be just like the sample Swift code you posted.

无论语言如何,编辑样式的检查都是可选的。这取决于您的表视图支持的内容。如果您只删除并且不支持插入,则验证编辑样式参数几乎没有任何好处。当然,检查更安全,以防您稍后再添加插入。

Regardless of the language, the check for the editing style is optional. It depends on what your table view supports. If you only delete and don't support insert, there's little benefit to verifying the editing style parameter. Of course it's safer to check, just in case you add insertion later on.

并在表格中使用 reloadData 当删除单行时效率低下且可能是一个糟糕的用户体验。

And using reloadData on a table when deleting a single row is just inefficient and possibly a bad UX.

tl; dr - Objective-C代码有效,但远非理想。 Swift代码整体上要好得多。

tl;dr - The Objective-C code works but is far from ideal. The Swift code is much better overall.

这篇关于从UITableView - Swift中删除行的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆