Swift:如何为表格输入编辑模式?

时间:2022-08-25 00:06:05

I have a RootViewController that embeds a container that contains a table:

我有一个RootViewController嵌入一个包含表的容器:

Swift:如何为表格输入编辑模式?

I'd like the garbage can icon on the top left of the RootViewController to enable editing mode for the embedded table view. I would like them to show up as checkboxes so that I can select multiple rows at once and then press "Delete" to delete all of the selected ones.

我希望在RootViewController的左上角有一个垃圾图标,可以为嵌入式表视图启用编辑模式。我希望它们显示为复选框,这样我可以一次选择多个行,然后按“Delete”来删除所有选中的行。

How would I do this?

我该怎么做呢?

1 个解决方案

#1


1  

Hopefully your class already conforms to UITableViewDelegate like so:

希望您的类已经符合UITableViewDelegate,例如:

class MyViewController: UIViewController, UITableViewDelegate

In viewDidLoad(), you would need to have:

在viewDidLoad()中,您需要:

myTable.delegate = self

Then you can hook up the trash can icon to an IBAction that sets the table to editing mode:

然后,您可以将垃圾箱图标连接到IBAction,该IBAction将表设置为编辑模式:

@IBAction func myTableSetEditing(sender: AnyObject) {        
    myTable.setEditing(true, animated: true)   
}

Then, as we see in an answer here: Select multiple rows in tableview and tick the selected ones, in viewDidLoad() put:

然后,正如我们在这里看到的答案:在tableview中选择多个行,在viewDidLoad() put中选中所选的行:

self.tableView.allowsMultipleSelection = true

and to get your checkmark, implement:

为了得到你的校验标记,实现:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark
}

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.None
}

#1


1  

Hopefully your class already conforms to UITableViewDelegate like so:

希望您的类已经符合UITableViewDelegate,例如:

class MyViewController: UIViewController, UITableViewDelegate

In viewDidLoad(), you would need to have:

在viewDidLoad()中,您需要:

myTable.delegate = self

Then you can hook up the trash can icon to an IBAction that sets the table to editing mode:

然后,您可以将垃圾箱图标连接到IBAction,该IBAction将表设置为编辑模式:

@IBAction func myTableSetEditing(sender: AnyObject) {        
    myTable.setEditing(true, animated: true)   
}

Then, as we see in an answer here: Select multiple rows in tableview and tick the selected ones, in viewDidLoad() put:

然后,正如我们在这里看到的答案:在tableview中选择多个行,在viewDidLoad() put中选中所选的行:

self.tableView.allowsMultipleSelection = true

and to get your checkmark, implement:

为了得到你的校验标记,实现:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark
}

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.None
}