简体   繁体   中英

How to dismiss SDCAlertView with tap gesture?

To show alert I use SDCAlertView (clone of UIAlertView). I want to dismiss alert by tap on screen like UIActionSheet.

Unlike UIAlertView , SDCAlertView is added as a view to the view hierarchy. That means that you can simply add a tap gesture recognizer to SDCAlertView 's superview, which calls [SDCAlertView dismissWithClickedButtonIndex:animated:] .

I found one way how do do it. Compatible with iOS 7+, but dismiss on tap works on 8+.

class SmartAlert
{
    static var backroundWindow: UIWindow!
    static var alertController: SDCAlertController!

    class func showAlertWithTitle(title: String!, message: String!, actionTitle: String)
    {
        if (iOS8)
        {
            self.backroundWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
            self.backroundWindow.backgroundColor = UIColor.clearColor()
            self.backroundWindow.rootViewController = EmptyViewController()
            self.backroundWindow.windowLevel = UIWindowLevelAlert
            self.backroundWindow.makeKeyAndVisible()
        }

        self.alertController = SDCAlertController(title: title, message: message, preferredStyle: .Alert)
        self.alertController.addAction(SDCAlertAction(title: actionTitle, style: .Default, handler:
        {
            (_) -> Void in
            self.backroundWindow = nil
        }))

        self.alertController.presentWithCompletion(nil)
    }

    class func dismissAlert()
    {
        self.alertController.dismissWithCompletion
        {
            self.backroundWindow = nil
        }
    }
}

class EmptyViewController: UIViewController
{
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
    {
        SmartAlert.dismissAlert()
    }

    override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent)
    {
        if motion == UIEventSubtype.MotionShake
        {
            SmartAlert.dismissAlert()
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM