Swift 2.2
import UIKit
extension UIAlertController {
// MARK: - UIAlertController+Present
private struct ButtonsName {
static let Ok = NSLocalizedString("uIAlertController.buttonName.ok", comment: "")
static let Cancel = NSLocalizedString("uIAlertController.buttonName.cancel", comment: "")
}
class func suggestionAlertViewWithTitle(title:String?, placeholder:String, message:String, presenter:UIViewController, destructive:Bool = false,
okButtonCompletion:((enteredSuggestion:String?)->Void)?, cancelButtonCompletion:(()->Void)?, presentCompletion:(()->Void)?) {
var alertTitle = UIAlertController.appName()
if let userTitle = title {
alertTitle = userTitle
}
let controller = UIAlertController(title: alertTitle, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: ButtonsName.Ok, style: destructive == true ? .Destructive : .Default) { (action) in
if let okButtonCompletion = okButtonCompletion {
let text = controller.textFields?.first?.text
dispatch_async(dispatch_get_main_queue(), {
okButtonCompletion(enteredSuggestion: text)
})
}
}
let cancelAction = UIAlertAction(title: ButtonsName.Cancel, style: .Cancel) { (action) in
if let cancelButtonCompletion = cancelButtonCompletion {
dispatch_async(dispatch_get_main_queue(), {
cancelButtonCompletion()
})
}
}
controller.addAction(okAction)
controller.addAction(cancelAction)
controller.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = placeholder
}
dispatch_async(dispatch_get_main_queue(), {
presenter.presentViewController(controller, animated: true, completion: presentCompletion)
})
}
// MARK: - Private
private static func appName () -> String {
return NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
}
}
usage:
UIAlertController.suggestionAlertViewWithTitle(nil, placeholder: placeholder, message: message,
presenter: self, destructive: false,
okButtonCompletion: { (enteredSuggestion) in
self.logger.sendAllLogs(self.currentUser, suggestedTitle: enteredSuggestion)
}, cancelButtonCompletion:nil, presentCompletion: nil)
a little bit overloaded, but u can always make some parameters optional or/and default