Swift- custom UITableViewCell delegate to UIViewCo

2019-01-24 21:26发布

In the application, I have custom protocols that my UIViewController conforms to. I have a custom tableViewCell class and have UIImageView and UITextView in there. I set the cell's delegate to the UIViewController after dequeuing. However only one of the custom protocols makes the callback (imagepicker protocol).

protocol customProtocol1{
    func pickImage(myInt: Int)
}
protocol customProtocol2{
    func protocol2 (myInt: Int)
}

class controller1: UIViewController, UITableViewDelegate, customProtocol1, customProtocol2  {
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section:Int) -> Int {
        return 3
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
        let cell = tableView.dequeReusableCellWithIdentifier("customCell",    forIndexPath: indexPath) as! CustomTableCellClass
        cell.delegate = self
        return cell
   }
    func pickImage ( myInt: Int){
        print("This line prints")
   }

   func protocol2 (myInt: Int){
        print ("This line doesn't print")


   }
}

And here's the customTableCellClass code:

class CustomTableCellClass: UITableViewCell, UITextFieldDelegate, UITextViewDelegate {
    var imageDelegate: customProtocol1?
    @IBAction func pickImage( sender: AnyObject) {
        imageDelagate?.pickImage(205)
    }

    var somethingElseDelegate: customProcotol2?
    @IBActon func clickOnButton( sender: AnyObject) {
        print("this line prints")
        somethingElseDelegate?.protocol2(2)
    }

   override func awakeFromNib(){
        super.awakeFromNib()
   }
}

My question is, why does the first protocol get callbacks but second does not?

2条回答
不美不萌又怎样
2楼-- · 2019-01-24 22:02

From what I see in your code, you only set one delegate, change your code in cellForRowAtIndexPath to

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeReusableCellWithIdentifier("customCell",    forIndexPath: indexPath) as! CustomTableCellClass
    cell.imageDelegate = self
    cell.somethingElseDelegate = self
    return cell
}
查看更多
成全新的幸福
3楼-- · 2019-01-24 22:17

Your custom cell has two delegate properties, imageDelegate and somethingElseDelegate, but in your implementation of tableView(tableView:cellForRowAtIndexPath:) you only assign one property.

If you set both properties your implementation should work.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 
    let cell = tableView.dequeReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! CustomTableCellClass
    cell.imageDelegate = self
    cell.somethingElseDelegate = self
    return cell
}
查看更多
登录 后发表回答