簡體   English   中英

不調用BEMCheckBox委托

[英]BEMCheckBox delegate is not called

在我的iOS Switch應用中,每個表格單元格中都有一個BEMCheckBox 使單元出隊時,我想設置一個被調用的委托。

我的問題是該復選框可以正常工作,但永遠不會調用該委托。 如何將委托添加到每個復選框?

我想知道哪個indexPath用於復選框。 計划是將模型對象傳遞給委托並相應地對其進行更新。

表單元

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

委托很簡單

class DoneBEMCheckBoxDelegate: NSObject, BEMCheckBoxDelegate {

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

}

cell.doneCheckbox.delegate = DoneBEMCheckBoxDelegate()在局部變量中創建一個新的DoneBEMCheckBoxDelegate對象,並將其分配為委托。 由於委托屬性是弱的,因此將在函數退出時立即釋放它,因為沒有剩余的強引用。

我建議擁有一個單獨的對象類作為委托可能不是您想要的。

我將單元格設置為復選框委托,然后聲明另一個協議,以便該單元可以擁有自己的委托,這將是您的表視圖控制器。

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
    }
}

這樣,您可以避免創建其他對象和數據結構,並且如果對單元格進行重新排序不會有問題,因為對索引路徑沒有依賴性。

我注意到委托在checkbox類中是一個弱引用,因為它應該是:)因此,在方法作用域結束后,我的委托被釋放了。

我通過在使用過程中將委托存儲在視圖控制器中來解決此問題。

var checkboxDelegates: [IndexPath:DoneBEMCheckBoxDelegate] = [:]
...
let checkboxDelegate = DoneBEMCheckBoxDelegate(realm: realm, set: set)
checkboxDelegates[indexPath] = checkboxDelegate
cell.doneCheckbox.delegate = checkboxDelegate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM