一尘不染

从UITableViewCell呈现UIAlertController

swift

我正在尝试向自定义添加提醒,UITableViewCell以提出一个UIAlertView我需要从调用presentViewController的提示UIViewController。但是,我不知道如何UIViewControllerUITableViewCell该类访问当前实例。下面的代码是我尝试使用扩展名进行的操作。

我得到这个错误

表达式解析为未使用的函数。

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 {

阅读 303

收藏
2020-07-07

共1个答案

一尘不染

您可以使用此扩展来查找显示单元格的viewController

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)
2020-07-07