#35 建立可多選的編輯清單

有時候我們會需要同時處裡複數的表格,包含刪除或轉發

建立流程

  1. 啟用allowsMultipleSelectionDuringEditing
  2. 設定系統內建的編輯按鈕function,只有在編輯模式下才啟用多選功能
  3. 編輯shouldPerformSegue,在多選時點擊Cell不跳到下一頁

步驟一、在viewDidLoad內建立在NavigationBar新增編輯按鈕,並啟用allowsMultipleSelectionDuringEditing。

    override func viewDidLoad() {
super.viewDidLoad()

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.leftBarButtonItem = self.editButtonItem

self.tableView.allowsMultipleSelectionDuringEditing = true
}

步驟二、呼叫setEditing編輯function,按下編輯按鈕時會切換成編輯模式,預設是刪除模式,但設定allowsMultipleSelectionDuringEditing後會變成多選模式,如果有設定moveRowAt()則會增加調整排列的模式。

 
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
self.tableView.setEditing(editing, animated: true)

}

步驟三、判斷在一般模式下點擊cell才跳下一頁


override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if self.tableView.isEditing {
return false
}
return true
}

最後再設定模擬測試環境

    // MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 4
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)

// Configure the cell...
cell.textLabel?.text = "Test"

return cell
}

接著我們就可以開始測試了,布局如下

成果

範例

--

--