首页 > 解决方案 > “CustomTableCell”类型的值没有成员委托

问题描述

我有一个名为 CustomTableCell 的 UITableViewCell 子类,它在 swift 4.1 中声明。文件。

在我的带有 UITableView 的视图控制器中,我在 cellForRowAt 中有:

let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier") as! CustomTableCell
cell.delegate = self

我收到以下错误:

Value of type 'CustomTableCell' has no member delegate.

我在顶部声明了 UITableViewDelegate。

标签: iosiphoneswiftios11swift4.1

解决方案


UITableViewDelegate 不需要cell.delegate = self.

如果您 CustomTableCell 有您的Custom Delegate,那么您只需要分配它。因此,如果您没有蚂蚁Custom Delegate,请CustomTableCell删除该行。

对于 tableView 委托方法,您必须在 viewDidLoad() 中添加:

yourTableView.delegate = self
yourTableView.dataSource = self

或仅使用连接它StoryBorad

回答:如何在 CustomTableCell 类中创建单元格委托?只是好奇

CustomTableCell.swift :

// Custom protocol 
protocol CustomCellDelegate: NSObjectProtocol {
   // Protocol method
   func someFunctionToPassSomeValue(name: String)
}
class CustomTableCell: UITableVieCell {
   weak var delegate: CustomCellDelegate?

  // Your class implementations and outlets..

  //Call your protocol method in some action, for example in button action
  @IBAction func buttonAction(sender: UIButton) {
    delegate?.someFunctionToPassSomeValue(name: "anyStringValue")
  } 
}

然后在ViewController课堂上,您需要将实例分配给自定义委托变量。

let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier") as! CustomTableCell
cell.delegate = self

并实现协议方法:

extension ViewController: CustomCellDelegate {
   func someFunctionToPassSomeValue(name: String) {
      print("Delegate is working. Value : \(name)")
   }
}

推荐阅读