Thursday 17 July 2014

Working with UIAlertController in Swift (NS_CLASS_AVAILABLE_IOS(8_0))

A UIAlertController, replaces prior UIActionSheet and UIAlertView classes for displaying alerts from iOS 8.


Declare alert controller:
var alert : UIAlertController?

Initialise alert controller:

  • UIAlertControllerStyleAlert
// UIAlertController Initializer
alert = UIAlertController(title: "Your Title", message: "Your Message", preferredStyle: .Alert)

//UIAlertController with UIAlertActions
alert = UIAlertController(title: "Your Title", message: "Your Message", preferredStyle: .Alert)

let
Yes = UIAlertAction(title: "Yes", style: .Default, handler: {(alertAction: UIAlertAction!) in self.alert!.dismissModalViewControllerAnimated(true)})

let
No = UIAlertAction(title: "No", style: .Default, handler:{(alertAction: UIAlertAction!) in self.alert!.dismissModalViewControllerAnimated(true)})

alert!.addAction(Yes)
alert!.addAction(No)

//UIAlertController with UIAlertActions & Input Textfields
alert = UIAlertController(title: "Your Title", message: "Your Message", preferredStyle: .Alert)

let Yes = UIAlertAction(title: "Yes", style: .Default, handler: {(alertAction: UIAlertAction!) in self.alert!.dismissModalViewControllerAnimated(true)})

let No = UIAlertAction(title: "No", style: .Default, handler:{(alertAction: UIAlertAction!) in self.alert!.dismissModalViewControllerAnimated(true)})

alert!.addAction(Yes)
alert!.addAction(No)

alert!.addTextFieldWithConfigurationHandler({(textField: UITextField!) in textField.placeholder = "UserName"})

alert!.addTextFieldWithConfigurationHandler({(textField: UITextField!) in textField.placeholder = "Password"; textField.secureTextEntry = true})


  • UIAlertControllerStyleActionSheet
//UIAlertController with ActionSheet
alert = UIAlertController(title: "Your Title", message: "Your Message", preferredStyle: .ActionSheet)

let
Yes = UIAlertAction(title: "Yes", style: .Default, handler: {(alertAction: UIAlertAction!) in self.alert!.dismissModalViewControllerAnimated(true)})


let
No = UIAlertAction(title: "No", style: .Default, handler:{(alertAction: UIAlertAction!) in self.alert!.dismissModalViewControllerAnimated(true)})

alert!.addAction(Yes)
alert!.addAction(No)

Present alert controller:
self.presentViewController(alert!, animated: true, completion: nil)

Reference: https://developer.apple.com/library/prerelease/iOS/documentation/UIKit/Reference/UIAlertController_class/index.html

GitHub:
https://github.com/bhvk121/UIAlertController_iOS8