Swift - 自定义UITableViewCell委托给UIViewController只有一个协议起作用

5

在应用程序中,我有自定义的协议,我的UIViewController符合这些协议。我有一个自定义的tableViewCell类,并在其中放置了UIImageView和UITextView。我在出列后将单元格的代理设置为UIViewController。然而,只有一个自定义协议会回调(imagepicker协议)。

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


   }
}

这里是 customTableCellClass 代码:

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

我的问题是,为什么第一个协议会得到回调,但第二个协议没有得到回调?

你是否想要输入 cell.imageDelegate = selfdelegate 是从哪里来的? - Aerows
2个回答

10

根据我在你的代码中看到的内容,你只设置了一个委托,请在 cellForRowAtIndexPath 中更改你的代码为:

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
}

是的,我刚刚才弄明白。谢谢你的回复! - Eugene Temlock
@EugeneTemlock 如果您认为我的答案是正确的,请接受我的答案 :) 谢谢 - Niko Adrianus Yuwono

2

您的自定义单元格有两个委托属性imageDelegatesomethingElseDelegate,但在您实现的tableView(tableView:cellForRowAtIndexPath:)中,您只分配了一个属性。

如果您设置了两个属性,则您的实现应该可以工作。

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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接