ios - 未调用委托方法并给出 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
}
}
解决方案
在cellForRow
你必须出列你的单元格。
let cell = tableView.dequeueReusableCell(withIdentifier: "yourId") as? FilterTableViewCell
cell.delegate = self
return cell
工作完成了
推荐阅读
- php - PHP:创建新对象时:对象中未定义的变量(但已明确定义)
- r - 这段代码中 b <-c() 的目的是什么?
- apache - 无法将参数传递到另一个重定向网站
- php - PHP foreach 循环不会显示不会将 JSON 文本打印到另一个显示基本画廊图像的 foreach 循环上
- postman - 无法从响应正文中检查 JSON 值
- c - 自定义 Shell Seg 错误
- html - 为什么我的阵列只在视图中更新一次?
- css - 在css中设置宽度100%后调整高度
- c++ - 从重载函数初始化 std::function 对象
- python - 如何解决在 Powershell Prompt 中运行 TabPy 时出现权限错误的问题