Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

ios - Presenting UIAlertController from UITableViewCell

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.

I get this error

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 {
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}
}

Or use rootViewController to Present:

UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(refreshAlert, animated: true, completion: nil)

Swift 4.2 Update

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
    }
}

Or use rootViewController to Present:

UIApplication.shared.keyWindow?.rootViewController?.present(alertVC, animated: true, completion: nil)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...