Where to Find a Clear Explanation About Swift Alert (Uialertcontroller)

Where to find a clear explanation about swift alert (UIAlertController)?

After searching a while on a subject I didn't
find a clear explanation , even in it's class reference
UIAlertController Reference

It is ok, but not clear enough for me.

So after collecting some peaces I decided to make my own explanation
(Hope it helps)

So here it goes:

  1. UIAlertView is deprecated as pointed out :
    UIAlertView in Swift
  2. UIAlertController should be used in iOS8+
    so to create one first we need to instantiate it,
    the Constructor(init) gets 3 parameters:

2.1 title:String -> big-bold text to display on the top of alert's dialog box

2.2 message:String -> smaller text (pretty much explains it's self)

2.3 prefferedStyle:UIAlertControllerStyle -> define the dialog box style, in most cases: UIAlertControllerStyle.Alert


  1. Now to actually show it to the user, we can use showViewController or presentViewController and pass our alert as parameter

  2. To add some interaction with a user we can use:

4.1
UIAlertController.addAction to create buttons

4.2
UIAlertController.addTextField to create text fields

Edit note: code examples below, updated for swift 3 syntax

Example 1: Simple Dialog

@IBAction func alert1(sender: UIButton) {
//simple alert dialog
let alert=UIAlertController(title: "Alert 1", message: "One has won", preferredStyle: UIAlertControllerStyle.alert);
//show it
show(alert, sender: self);
}

Example 2: Dialog with one input textField & two buttons

@IBAction func alert2(sender: UIButton) {
//Dialog with one input textField & two buttons
let alert=UIAlertController(title: "Alert 2", message: "Two will win too", preferredStyle: UIAlertControllerStyle.alert);
//default input textField (no configuration...)
alert.addTextField(configurationHandler: nil);
//no event handler (just close dialog box)
alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: nil));
//event handler with closure
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction) in
let fields = alert.textFields!;
print("Yes we can: "+fields[0].text!);
}));
present(alert, animated: true, completion: nil);
}

Example 3: One customized input textField & one button

@IBAction func alert3(sender: UIButton) {
// one input & one button
let alert=UIAlertController(title: "Alert 3", message: "Three will set me free", preferredStyle: UIAlertControllerStyle.alert);

//configured input textField
var field:UITextField?;// operator ? because it's been initialized later
alert.addTextField(configurationHandler:{(input:UITextField)in
input.placeholder="I am displayed, when there is no value ;-)";
input.clearButtonMode=UITextFieldViewMode.whileEditing;
field=input;//assign to outside variable(for later reference)
});
//alert3 yesHandler -> defined in the same scope with alert, and passed as event handler later
func yesHandler(actionTarget: UIAlertAction){
print("YES -> !!");
//print text from 'field' which refer to relevant input now
print(field!.text!);//operator ! because it's Optional here
}
//event handler with predefined function
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: yesHandler));

present(alert, animated: true, completion: nil);
}

Hope It helps, and good luck ;-)

Swift alert view with OK and Cancel: which button tapped?

If you are using iOS8, you should be using UIAlertController — UIAlertView is deprecated.

Here is an example of how to use it:

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
print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))

presentViewController(refreshAlert, animated: true, completion: nil)

As you can see the block handlers for the UIAlertAction handle the button presses. A great tutorial is here (although this tutorial is not written using swift):
http://hayageek.com/uialertcontroller-example-ios/

Swift 3 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Swift 5 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Swift 5.3 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

How can i use notification & alert in swift?

The problem is, you are trying to display another UIAlertController on the currently presented UIAlertController.

You are presenting your UIAlertController twice.

Remove the line present(alert, animated: true, completion: nil) under let alert = ....

How can I add a url to an alert?

You cannot add arbitrary interface to a UIAlertController. The title and message are not tappable. You cannot add further text. Instead, add another button (UIAlertAction) that directs them to the Web page. Either that, or use some other interface instead of a UIAlertController (for example, you can put up a presented view controller that looks like an alert).

Prevent Alert action from dismissing the UIAlertController if incorrect answer - Swift 4

You can't do this.
It's system behaviour - when you click on button alert closes and you can't prevent this.

Only one solution is to create a custom view controller that will look like native UIAlertController.

UIAlertController won't display - In Swift

The problem is that by the time you call this following function:

present(alertController, animated: true, completion: nil)

your mail view controller is still visible. You have to make sure that the alertController is presented on the top of window hierarchy. In your example, you have the following window hierarchy:

+---------------------------+
| MailComposeViewController |
+---------------------------+
||
+---------------------------+
| ContactUsViewController |
+---------------------------+

What you should do instead is to dismiss the email view controller first. When that is done, show you alert view controller.

let alertController = UIAlertController(title: "test", message: "test", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "Okay", style: .Default, handler: nil)
alertController.addAction(okButton)
controller.dismissViewControllerAnimated(true){ () -> Void in
self.present(alertController, animated: true, completion: nil)
}

Alternatively, you can also present your alertController on top of the MailComposeViewController, like so:

let alertController = UIAlertController(title: "test", message: "test", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "Okay", style: .Default, handler: nil)
alertController.addAction(okButton)
controller.present(alertController, animated: true, completion: nil)

How to do a simple alert in iOS Swift?

Try this sample I hope this will help!!! https://github.com/orazz/SampleAlert

Sample Image

Check on UIAlertController TextField for enabling the button

I would first create the alertcontroller with the save action initially disabled. Then when adding the textfield inculde a Notification to observe its change in the handler and in that selector just toggle the save actions enabled property.

Here is what I am saying:

//hold this reference in your class
weak var AddAlertSaveAction: UIAlertAction?

@IBAction func addTherapy(sender : AnyObject) {

//set up the alertcontroller
let title = NSLocalizedString("New Prescription", comment: "")
let message = NSLocalizedString("Insert a name for this prescription.", comment: "")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
let otherButtonTitle = NSLocalizedString("Save", comment: "")

let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)

// Add the text field with handler
alertController.addTextFieldWithConfigurationHandler { textField in
//listen for changes
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTextFieldTextDidChangeNotification:", name: UITextFieldTextDidChangeNotification, object: textField)
}

func removeTextFieldObserver() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields[0])
}

// Create the actions.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
NSLog("Cancel Button Pressed")
removeTextFieldObserver()
}

let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in
NSLog("Save Button Pressed")
removeTextFieldObserver()
}

// disable the 'save' button (otherAction) initially
otherAction.enabled = false

// save the other action to toggle the enabled/disabled state when the text changed.
AddAlertSaveAction = otherAction

// Add the actions.
alertController.addAction(cancelAction)
alertController.addAction(otherAction)

presentViewController(alertController, animated: true, completion: nil)
}

//handler
func handleTextFieldTextDidChangeNotification(notification: NSNotification) {
let textField = notification.object as UITextField

// Enforce a minimum length of >= 1 for secure text alerts.
AddAlertSaveAction!.enabled = textField.text.utf16count >= 1
}

I am doing this in another project - I got this pattern directly from apple examples. They have a very good example project outlining a few of these patterns in the UICatalog examples: https://developer.apple.com/library/content/samplecode/UICatalog/Introduction/Intro.html

UIAlertController from extension

You create an alert by instantiating a UIAlertController. You can use the output of your onlyNumbers function as the message of the alert controller.

Then you need to add UIAlertAction(s) to it and finally call self.present to display the alert controller from a UIViewController subclass.

if UIPasteboard.general.string?.onlyNumbers() == "" {
let alertController = UIAlertController(title: "Calc Pro", message: UIPasteboard.general.string?, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alertController, animated: false, completion: nil)
}


Related Topics



Leave a reply



Submit