如果你想了解如何使用表格來顯示數據,或是如何刪除表格中的一行數據,請點擊以下鏈接:
基於Swift的iOS應用程序開發:使用表格顯示並控制數據(一):顯示數據
基於Swift的iOS應用程序開發:使用表格顯示並控制數據(二):刪除表格中的數據
所謂批量處理,其實就是一次選中表格中的多行,然後對這些被選中的數據行做處理
1、允許表格被批量選中
self.tableView.allowsMultipleSelectionDuringEditing = true
此時,如果你希望自己的表格在默認情況下,就能夠在每一行的最左側出現一個複選框,那麼還需要加上下面的代碼:self.tableView.setEditing(true, animated: true)
這麼做的話,就能滿足最基本的表格多選要求了,效果如下:self.tableView.setEditing(false, animated: true)
然後我們需要用到UITableViewController的一個自帶的屬性:self.editButtonItem。這個屬性是一個按鈕,每當用戶按下這個按鈕,就會觸發表格的編輯事件,整個表格會右移,露出每一行左側的操作按鈕來。我們只需要把這個按鈕顯示在界面上就可以了。由於我使用的是UINavigationController,所以將這個按鈕綁定到頂部導航欄的右側:self.navigationItem.rightBarButtonItem = self.editButtonItem
self.navigationItem.rightBarButtonItem?.title = "編輯"
override func viewDidLoad() {
super.viewDidLoad()
/*
* 允許表格被多行批量編輯
*/
self.tableView.allowsMultipleSelectionDuringEditing = true
/*
* 設置在界面初始化的時候,表格前方的多選框隱藏或者顯示
*/
self.tableView.setEditing(false, animated: true)
self.navigationItem.rightBarButtonItem = self.editButtonItem
self.navigationItem.rightBarButtonItem?.title = "編輯"
}
2、處理被選中的行
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("第\(indexPath.row)行被選中了")
}
重載以下方法,用來處理被取消選中的行:
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
print("第\(indexPath.row)行被取消選中了")
}