首页 > 解决方案 > 未调用委托方法并给出 nil 值

问题描述

由于某种原因,没有调用委托方法。我正在控制台中打印委托属性,但它返回 nil。我在这里寻找其他答案,但没有一个对我有帮助。

protocol FilterSwitchDelegate {
    func switchValueChanged(tagValue:Int)
}

class FilterTableViewCell: UITableViewCell {
    @IBOutlet weak var filterLabel: UILabel!
    @IBOutlet weak var filterSwitch: UISwitch!

    var delegate:FilterSwitchDelegate?

    @IBAction func filterSwitchValueChanged(_ sender: UISwitch) {
        print(sender.tag)

        delegate?.switchValueChanged(tagValue: sender.tag)      
    }
}

//在FilterViewController中我调用了这个委托方法

class FilterViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    var dataSource = FilterTableViewCell()
    var filterModel = [FilterVCDataModel]()
    var ids = [Int]()

    override func viewDidLoad() {
        super.viewDidLoad()
        dataSource.delegate = self
    }
}

extension FilterViewController: FilterSwitchDelegate {
    func switchValueChanged(tagValue: Int) {
        ids.remove(at: tagValue)
        print(ids)
    }
}

TableView 数据源和委托方法

extension FilterViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filterModel.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "filterCell", for: indexPath) as! FilterTableViewCell
        cell.filterSwitch.tag = indexPath.row
        cell.filterLabel.text = filterModel[indexPath.row].filterData["title"] as? String
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }        
}

标签: iosswiftdelegatesprotocols

解决方案


cellForRow你必须出列你的单元格。

let cell = tableView.dequeueReusableCell(withIdentifier: "yourId") as? FilterTableViewCell

cell.delegate = self

return cell

工作完成了


推荐阅读