如何删除 table 视图单元格中的特定行?
How to delete specific rows in a table view cell?
我正在使用由三个部分组成的 table 视图。用户可以删除第三部分的行。但是当我使用 table 视图委托方法删除行时,它会影响其他部分。那么我该如何克服这个问题呢?
这是我的代码
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
numbers.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
正确的做法是
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()
}
}
在 forRowAt indexPath: IndexPath
函数中你有 IndexPath
值。
它包含.section
。因此,您可以简单地检查一下,您选择了哪个部分,然后删除或不删除。
要删除特定部分的行:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
希望对您有所帮助
如果您想将编辑限制在第 2 部分,请执行 canEditRowAt
(代码为 Swift 3+)
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return indexPath.section == 2
}
或添加支票
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)
}
我正在使用由三个部分组成的 table 视图。用户可以删除第三部分的行。但是当我使用 table 视图委托方法删除行时,它会影响其他部分。那么我该如何克服这个问题呢?
这是我的代码
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
numbers.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
正确的做法是
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()
}
}
在 forRowAt indexPath: IndexPath
函数中你有 IndexPath
值。
它包含.section
。因此,您可以简单地检查一下,您选择了哪个部分,然后删除或不删除。
要删除特定部分的行:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
希望对您有所帮助
如果您想将编辑限制在第 2 部分,请执行 canEditRowAt
(代码为 Swift 3+)
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return indexPath.section == 2
}
或添加支票
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)
}