Search code examples
iosiphoneswiftios11swift4.1

Value of type 'CustomTableCell' has no member delegate


I have a subclass of UITableViewCell called CustomTableCell which is declared in a swift 4.1. file.

In my view controller with the UITableView I have in cellForRowAt:

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

I get the following error:

Value of type 'CustomTableCell' has no member delegate.

I declared the UITableViewDelegate at the top.


Solution

  • UITableViewDelegate doesn't need cell.delegate = self.

    If you CustomTableCell has your Custom Delegate then only you need to assign it. So if you don't have ant Custom Delegate for your CustomTableCell remove that line.

    For tableView delegate methods you have to add this in viewDidLoad() :

    yourTableView.delegate = self
    yourTableView.dataSource = self
    

    Or connect it using StoryBorad only.

    Answer for: How do you create a cell delegate in the CustomTableCell class? Just curious

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

    Then in ViewController class you need to assign instance to custom delegate variable.

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

    And implement protocol method :

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