透過 delegate 設定 cell 當中 UI 元件的事件指派給 Table View Controller

Patty
彼得潘的 Swift iOS App 開發教室
5 min readOct 7, 2021

--

將觸發 UI 元件( button、switch…) 的 IBAction 定義在 cell 當中,接著透過 delegate 將被觸發的 cell 指派 table view controller 做更新資料和表格 UI 內容。

步驟

實作改變 dynamic cell 當中的開關,更新表格資料和 UI 內容。將 cell 切換開關後,指派給 table view controller 作為代理人,得到 cell 和更新表格資料和 UI 內容。

AlarmTableViewCell.swift

設定 protocol 和宣告 protocol 當中的 function

protocol AlarmTableViewCellTapDelegate {
func isActiveSwitch(cell: AlarmTableViewCell)
}

宣告 delegate 和呼叫 delegate 的 function

dynamic cell 當中 UI 元件的 IBAction 需要定義在 cell.swift ,接著透過 delegate 的 function 參數( 包含 cell ) 傳遞給 table view controller 且委託 table view controller 做更新。

var delegate: AlarmTableViewCellTapDelegate?@IBAction func turnAlarmIsActiveSwitch(_ sender: UISwitch) {
delegate?.isActiveSwitch(cell: self)
}

AlarmTableViewController.swift

遵從 protocol 和定義 protocol 當中的 function

定義 function:透過 cell 找到對應的位置以更新資料

extension AlarmTableViewController: AlarmTableViewCellTapDelegate {
func isActiveSwitch(cell: AlarmTableViewCell) {
guard let indexPath = self.tableView.indexPath(for: cell) else { return }
alarmList[indexPath.row].alarmIsActive = !alarmList[indexPath.row].alarmIsActive
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}

設定 delegate

設定代理人為 table view controller

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "\(AlarmTableViewCell.self)", for: indexPath) as? AlarmTableViewCell else { return UITableViewCell()}
let row = indexPath.row
let alarm = alarmList[row]
cell.alarmTime.text = "\(alarm.alarmTime)"
cell.alarmNameAndRepeatDays.text = "\(alarm.alarmLabel), \(alarm.alarmRepeatDaysDescription)"
cell.alarmSwitch.isOn = alarm.alarmIsActive
cell.alarmSwitch.isHidden = tableView.isEditing ? true : false
cell.editingAccessoryType = .disclosureIndicator
cell.delegate = self
return cell
}

--

--