huy-le
5/25/2016 - 12:28 PM

UIAlertView.swift

import UIKit

/**
How to use it
````
    AlertView
        .alert("Are you sure?", message: "Send this message to your friend")
        .will("OK") {
            // Do something because User choose OK
        }
        // Have a cancle button
        .willCancel()
    
````
*/
final class AlertView {
    /**
     A builder function to make an UIAlertController. 
     
     - parameter title:   Title will appear in AlertView
     - parameter message: Message in alert view
     - parameter style:   You can choose .ActionSheet or .Alert
     
     - returns: an UIAlertController, which can be config action button by DSL function below.
     */
    static func alert(title: String? = nil, message: String? = nil, style: UIAlertControllerStyle = .Alert) -> UIAlertController {
        let alert = UIAlertController(
            title: title,
            message: message,
            preferredStyle: style
        )
        return alert
    }
}

extension UIAlertController {
    
    /**
     It add a cancel button into Alert View, which will close the Alert when touch on that.
     
     - parameter title:   Label of cancel button, integrated with LocalizedString.
     - parameter handler: Closure which will be notified when cancel button be tapped.
     
     - returns: an UIAlertController
     */
    func willCancel(title: String = "Cancel", handler: ((UIAlertAction) -> ())? = nil) -> UIAlertController {
        return will(title, style: .Cancel, handler: handler)
    }
    
    /**
     Add a button into Alert View.
     
     - parameter title:   Label of button. Integrated with LocalizedString
     - parameter style:   It can be .Default, .Cancel or .Destructive
     - parameter handler: Be notified when this button be tapped
     
     - returns: an UIAlertController
     */
    func will(title: String, style: UIAlertActionStyle = .Default, handler: ((alertAction: UIAlertAction) -> Void)? = nil) -> UIAlertController {
        self.addAction(UIAlertAction(title: title, style: style, handler: handler))
        return self
    }
    
    /**
     Show the alert view on screen.
     
     - parameter viewController: The ViewController what you want to show AlertView above.
     - parameter animated:       Be true if you want to animate the presenting of AlertView
     - parameter completion:     Be notified when presentation finished
     */
    func present(on viewController: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
        viewController.presentViewController(self, animated: animated, completion: completion)
    }
}