ios - 未调用 BEMCheckBox 委托(delegate)

标签 ios swift uitableview delegates

在我的 iOS Switch 应用程序中,我有一个 BEMCheckBox在每个表格单元格中。将单元格出列时,我想设置一个被调用的委托(delegate)。

我的问题是复选框工作正常,但委托(delegate)并非从未被调用。如何为每个复选框添加委托(delegate)?

我想知道复选框的索引路径。计划是将模型对象传递给委托(delegate)并相应地更新它。

表格单元格

let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
cell.doneCheckbox.delegate = DoneBEMCheckBoxDelegate()
return cell

委托(delegate)很简单

class DoneBEMCheckBoxDelegate: NSObject, BEMCheckBoxDelegate {

    @objc func didTap(_ checkBox: BEMCheckBox) {
        print("Checkbox tapped")
    }

}

最佳答案

cell.doneCheckbox.delegate = DoneBEMCheckBoxDelegate() 正在局部变量中创建一个新的 DoneBEMCheckBoxDelegate 对象并将其分配为委托(delegate)。由于 delegate 属性是弱的,一旦函数退出它就会被释放,因为没有剩余的强引用。

我建议让一个单独的对象类作为委托(delegate)可能不是您想要的。

我会将单元格设置为复选框委托(delegate),然后声明另一个协议(protocol),以便单元格可以拥有自己的委托(delegate),这将是您的 TableView Controller 。

protocol MyCellDelegate {
    func checkBox(for cell: MyCell, isOn: Bool)
}

class MyCell: UITableViewCell, DoneBEMCheckBoxDelegate {

    var delegate: MyCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        self.doneCheckBox.delegate = self
    }

    @objc func didTap(_ checkBox: BEMCheckBox) {
        print("Checkbox tapped")
        self.delegate?.checkBox(for: self, isOn: checkBox.isOn)
    }

}


class YourViewController: MyCellDelegate {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        ...
        cell.delegate = self

        return cell
    }

    func checkBox(for cell: MyCell, isOn: Bool) {

        guard let indexPath = tableView.indexPath(for: cell) else {
            return
        }
        // Now do whatever you need to with indexPath
    }
}

这样您就可以避免创建额外的对象和数据结构,并且如果单元格重新排序也不会有问题,因为不依赖于索引路径。

关于ios - 未调用 BEMCheckBox 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47004781/

相关文章:

swift - 生成随机 Int64 + swift 3

iphone - 无法填充 UITableView

ios - 如何从 WKWebView 打印特定的 iFrame

iOS 8 : Sound setting doesn't work for UIUserNotificationType

ios - iOS 中的 GCM 到 FCM

ios - 删除导致应用程序崩溃

swift - 如何设置段控件来更改 TableView 单元格中的集合单元格项目?

swift - 无法从 Firebase 查看字典数据

iphone - 遍历 NSFetchRequest 结果时无错误地崩溃

ios - iOS:从字典获取数组中的值