我没有成功从 UITableViewCell 执行 UIAlertController
我已经尝试以编程方式创建一个segue,然后执行它(代码编号1),但它在appDelegate处崩溃(崩溃发生在appDelegate处) 我尝试使用代码 2,但它什么也没做(打印出:“其 View 不在窗口层次结构中!”也许它已连接?), 我尝试调用 viewController.Swift 中的函数来呈现和/或继续,但它也没有成功
仅当按下单元格中的特定按钮时才会出现警报
代码1:
UIApplication.shared.keyWindow?.rootViewController?.present(refreshAlert, animated: true, completion: nil)
代码2:
var segue = UIStoryboardSegue.init(identifier: "goAlart", source: ViewController(), destination: refreshAlert)
segue.perform()
我在 appDelegate 得到的异常是:线程 1:信号 SIGABRT 当我删除“segue.perform()”时,我没有收到任何错误
最佳答案
正如评论中提到的,显示警报的好地方是 didSelectRow at
。
我看不到其余的代码,但我假设您已经初始化了 UIAlertController 并且属性 refreshAlert
指向它。如果 refreshAlert
存储在 ViewController
中,那么这应该可以工作:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
present(refreshAlert, animated: true, completion: nil)
}
编辑: 由于您需要在单元格中按下按钮时显示警报,因此最好的方法是委托(delegate)协议(protocol):
protocol MyCusomCellDelegate: NSObjectProtocol {
func didPressAlertButton()
}
在您的单元格中,您声明委托(delegate)属性:
weak var delegate: MyCusomCellDelegate?
按下按钮后,您将调用委托(delegate)方法:
delegate?.didPressAlertButton()
在 ViewController 中,您遵守协议(protocol):
extension ViewController: MyCusomCellDelegate {
func didPressAlertButton() {
present(refreshAlert, animated: true, completion: nil)
}
}
最后,在cellForRowAt indexPath
cell.delegate = self
如果您需要为不同的单元格显示不同的警报,那么您应该在委托(delegate)调用中传递一些数据。
关于swift - 从 UITableViewCell 呈现 UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57554823/