關於如何使用表格來顯示多行數據,請參考以下文章:
基於Swift的iOS應用程序開發:使用表格顯示並控制數據(一):顯示數據
本編記錄如何刪除表格中的數據,先來看效果:
如果我們需要刪除表格中的某一行數據,可以這麼做:
1、允許表格可編輯
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
這個方法很簡單地返回一個布爾值,如果是true的話,就代表允許用戶編輯表格2、設置每一行處於編輯狀態下的左側按鈕的樣式
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.delete
}
注意,UITableViewCellEditingStyle類提供了幾種默認的按鈕樣式,查看一下這個枚舉類型的源碼:public enum UITableViewCellEditingStyle : Int {
case none
case delete
case insert
}
可以看到一共有三種不同的樣式none:不顯示任何按鈕圖形
3、設置每一行側滑之後出現在右側的按鈕文字
override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "刪除"
}
4、確認刪除操作
實現以下方法,就能處理刪除動作了:override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
/*
* 先刪除數組中對應的數據
*/
self.stringArr.remove(at: indexPath.row)
/*
* 刪除一行表格
*/
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
注意上述方法中的“self.stringArr.remove(at:indexPath.row)”這句,因爲在本例中,顯示在表格上的數據是來自一個數組的。所以在刪除表格的一行之前,一定要先刪除數組中的相應的數組才行,否則後臺會報錯5、在界面上添加一個“開始編輯”的按鈕
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.editButtonItem
self.navigationItem.rightBarButtonItem?.title = "開始編輯"
}