Swift UITableView单元格调用UIAlertController弹出窗口…“;“现在”;错误

Swift UITableView单元格调用UIAlertController弹出窗口…“;“现在”;错误,swift,uitableview,uialertcontroller,Swift,Uitableview,Uialertcontroller,我有一个tableview定义,试图在其中调用UIAlertController弹出窗口。我在prototype tableView单元格中安装了一个按钮,当触摸该按钮时,iAction将处理该事件。问题是编译器不让我这么做 present(alertController, animated: true, completion: nil) 生成编译器错误:“使用未解析的标识符“present” 代码如下: class allListsCell: UITableViewCell { @

我有一个tableview定义,试图在其中调用UIAlertController弹出窗口。我在prototype tableView单元格中安装了一个按钮,当触摸该按钮时,iAction将处理该事件。问题是编译器不让我这么做

present(alertController, animated: true, completion: nil)
生成编译器错误:“使用未解析的标识符“present”

代码如下:

class allListsCell: UITableViewCell {

    @IBOutlet var cellLable:       UIView!
    @IBOutlet var cellSelected:    UILabel!
    var colorIndex = Int()        

    @IBAction func cellMarkButton(_ sender: UIButton, forEvent event: UIEvent) {
        if  colors[self.colorIndex].selected == false {
            colors[self.colorIndex].selected = true
            cellSelected.text = "•"

            let alertController = UIAlertController(title: "???", message: "alertA", preferredStyle: .alert)

            let OKAction = UIAlertAction(title: "dismiss", style: .default) { (action:UIAlertAction!) in
                print("Sand: you have pressed the Dismiss button");
            }
            alertController.addAction(OKAction)

            present(alertController, animated: true, completion: nil) // ERROR

        } else {
            colors[self.colorIndex].selected = false
            cellSelected.text = ""
        }
    }

如果我对这一行进行注释,应用程序将为每个单元格正确运行…

您不能在tableView单元格内调用present AlertController,它需要一个子类
UIViewController
或其他等效的子类,您应该使用委托或某种通知来处理该问题,请参见我在此处对相同问题的回答


编辑:Form,它是
UIViewController
中的一个实例方法。因此,它不能在其他类型的任何其他类(
UITableViewCell
)中调用。在您的情况下

不可能从TableViewCell调用“present”方法,我建议在主控制器中使用一个函数来显示您的UIViewController

使用此代码,您可以实例化父驱动程序并执行任何可用功能:

extension UIView {
    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}

//UITableViewCell
if let controller = self.parentViewController as? YourController
{
    controller.showAlert()
}
下面是它与CollectionViewCell一起使用的示例:

谢谢。我想了解为什么会出现这种情况,您能简单解释一下吗?简单地说,UITableViewCell不是视图控制器。可能与