【发布时间】:2018-07-23 01:30:54
【问题描述】:
我有一个带开关的自定义单元格。我想在tableView(cellForRowAt:) 中添加目标。但是通过这样做(在示例代码中),我将创建一个强大的引用循环。
然后我尝试使用协议/委托方法,但这意味着所有单元格都会调用相同的方法。
如何设置我的单元格并相应地添加目标?
强引用循环:
class customCell: UITableViewCell {
var customSwitch: UISwitch()
// setup switch
}
class VC1: UITableViewController {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.customSwitch.addTarget(self, action: #selector(handleSwitch1), for: valueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.customSwitch.addTarget(self, action: #selector(handleSwitch2), for: valueChanged)
return cell
default:
fatalError()
}
}
@objc func handleSwitch1(_ sender: UISwitch) { }
@objc func handleSwitch2(_ sender: UISwitch) { }
}
使用委托:
class customCell: UITableViewCell {
var customSwitch: UISwitch()
weak var delegate: VC1Delegate?
// setup switch
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
customSwitch.addTarget(self, action: #selector(handleSwitch), for: valueChanged)
}
@objc func handleSwitch(_ sender: UISwitch) {
delegate?.handleSwitch1(sender)
}
}
protocol VC1Delegate: class {
func handleSwitch1(_ sender: UISwitch)
func handleSwitch2(_ sender: UISwitch)
}
class VC1: UITableViewController, VC1Delegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.delegate = self
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.delegate = self
return cell
default:
fatalError()
}
}
@objc func handleSwitch1(_ sender: UISwitch) { }
@objc func handleSwitch2(_ sender: UISwitch) { }
}
【问题讨论】:
标签: swift uitableview memory-leaks delegates uiswitch