【问题标题】:Value of type 'CustomTableCell' has no member delegate [closed]“CustomTableCell”类型的值没有成员委托[关闭]
【发布时间】:2018-07-13 03:33:23
【问题描述】:

我有一个名为 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。

【问题讨论】:

  • 您的自定义单元格是否有一个名为委托的属性?它可能缺少它的声明。
  • cell.delegate != UITableViewDelegate。单元必须有自己的委托协议。
  • 为什么负面和接近与编程无关?只是好奇

标签: ios iphone swift ios11 swift4.1


【解决方案1】:

UITableViewDelegate 不需要cell.delegate = self

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

对于 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)")
   }
}

【讨论】:

  • 如何在 CustomTableCell 类中创建单元格委托?只是好奇
  • @cdub 更新了我的答案以显示自定义委托的示例。
  • 确保使用“delegate?.****”(如果您不确定 delegate 是否为 nil)或“delegate!.****”(如果您确定它是不为零),只要它是可选的。
  • @Sedo 好点,因为我忘了添加它,因为我是直接在这里输入的。已更新。
  • @SharadChauhan 我想。和 buttonAction 前面的“func”。
猜你喜欢
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多