Swift 代理返回 nil

3
我尝试从UITableViewCell中调用UIAlertController。
我有我的代理。
protocol DEPFlightStripCellDelegate {
  func callAlert(AlertCon: UIAlertController!)
}

我称之为下面我 TableViewCell 类中的内部。
class DEPFlightStripCell: UITableViewCell {
    var delegate: DEPFlightStripCellDelegate?

    @IBAction func changeClearedFlightLevel(sender: UIButton) {
        let AddAlert: UIAlertController = UIAlertController(title: "Select Altitude", message: "", preferredStyle: .Alert)
        self.delegate?.callAlert(AddAlert)
    }
}

为了呈现视图控制器,我在我的mainView类中设置了DEPFlightStripCellDelegate,并调用我上面声明的函数“callAlert”来显示警报。
class mainView: UIViewController,UITextFieldDelegate, DEPFlightStripCellDelegate {
  func callAlert(AlertCon: UIAlertController!) {
    println("Test")
    self.presentViewController(AlertCon, animated: true, completion: nil)
  }
}

然而,代理返回了nil。有人知道为什么吗?
1个回答

2

您的mainView实例尚未被分配为DEPFlightStripCell中的delegate。当您实例化该单元格时,通常在表视图委托方法中,您应该为该单元格指定其委托。

像这样:

class mainView: UIViewController,UITextFieldDelegate, DEPFlightStripCellDelegate {
  // ...

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) 
       as! DEPFlightStripCell

    cell.delegate = self
    return cell
  }

  // ...
}

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