从 UITableViewCell 呈现 UIAlertController [英] Presenting UIAlertController from UITableViewCell
问题描述
我正在尝试向自定义 UITableViewCell
添加警报以显示 UIAlertView
我需要从 UIViewController
调用 presentViewController.但是,我不知道如何从 UITableViewCell
类访问当前的 UIViewController
实例.下面的代码是我尝试通过扩展来做到这一点.
I am trying to add alerts to a custom UITableViewCell
to present an UIAlertView
I need to call presentViewController from UIViewController
. However, I am unaware of how to gain access to the current UIViewController
instance from the UITableViewCell
class. The below code is my attempt to do this with an extension.
我收到这个错误
表达式解析为未使用的函数.
Expression resolved to unused function.
extension UIViewController
{
class func alertReminden(timeInterval: Int)
{
var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
Alarm.createReminder("Catch the Bus",
timeInterval: NSDate(timeIntervalSinceNow: Double(timeInterval * 60)))
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
println("Handle Cancel Logic here")
}))
UIViewController.presentViewController(refreshAlert)
}
}
class CustomRouteViewCell: UITableViewCell {
推荐答案
你可以使用这个扩展来查找呈现单元格的 viewController
You can use this extension to find the viewController that present the cell
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.nextResponder()
if parentResponder is UIViewController {
return parentResponder as! UIViewController!
}
}
return nil
}
}
或者使用rootViewController
来展示:
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(refreshAlert, animated: true, completion: nil)
Swift 4.2 更新
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if parentResponder is UIViewController {
return parentResponder as? UIViewController
}
}
return nil
}
}
或者使用rootViewController
来展示:
UIApplication.shared.keyWindow?.rootViewController?.present(alertVC, animated: true, completion: nil)
这篇关于从 UITableViewCell 呈现 UIAlertController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!