UITableView 单元格调用 UIAlertController 弹出窗口...“present"错误 [英] UITableView cell invokes UIAlertController popup ..."present" error
问题描述
我有一个 tableview 定义,我试图在其中调用 UIAlertController 弹出窗口.我在原型 tableView 单元格中安装了一个按钮,当触摸该按钮时,IBAction 会处理该事件.问题是编译器不会让我.
I have a tableview definition in which I am attempting to invoke an UIAlertController popup. I installed a button in the prototype tableView cell, when the button is touched, an IBAction handles the event. The problem is that the compiler won't let me.
present(alertController, animated: true, completion: nil)
生成编译器错误:使用未解析的标识符‘存在’
Generates compiler error: "Use of unresolved identifier '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 = ""
}
}
如果我评论那一行,应用程序会为每个单元格正确运行...
If I comment that one line, the app runs correctly for each cell...
推荐答案
无法从 TableViewCell 中调用present"方法,我建议在主控制器中有一个函数来显示您的 UIAlertController.
It is not possible to call the "present" method from a TableViewCell, I recommend having a function in the main controller to show your UIAlertController.
使用此代码,您可以实例化父驱动程序并执行任何可用函数:
Using this code you can instantiate the parent driver and execute any available function:
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 一起使用的示例:https://github.com/AngelH2/CollectionViewCell-Comunication/tree/master/CollectionCellAction
Here is an example of its use with a CollectionViewCell: https://github.com/AngelH2/CollectionViewCell-Comunication/tree/master/CollectionCellAction
这篇关于UITableView 单元格调用 UIAlertController 弹出窗口...“present"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!