How would I create a UIAlertView in Swift?
I have been working to create a UIAlertView in Swift, but for some reason I can't get the statement right because I'm getting this error:
Could not find an overload for 'init' that accepts the supplied
arguments
Here is how I have it written:
let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
Then to call it I'm using:
button2Alert.show()
As of right now it is crashing and I just can't seem to get the syntax right.
ios swift cocoa-touch uialertview uialertcontroller
add a comment |
I have been working to create a UIAlertView in Swift, but for some reason I can't get the statement right because I'm getting this error:
Could not find an overload for 'init' that accepts the supplied
arguments
Here is how I have it written:
let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
Then to call it I'm using:
button2Alert.show()
As of right now it is crashing and I just can't seem to get the syntax right.
ios swift cocoa-touch uialertview uialertcontroller
5
UIAlertView
andUIActionSheet
has been replaced byUIAlertController
in iOS 8, have you looked at this?
– Popeye
Jun 3 '14 at 18:51
Make sure the class thatself
belongs to adopts the protocolUIAlertViewDelegate
(the recommended way to do this, in Swift, is with an extension).
– Nicolas Miari
Jul 14 '15 at 7:37
@Adam: I have reverted your retagging. The swift3 tag is for "questions directly related to changes in version 3 of Apple's Swift programming language." And I don't think that "If the answers make it clear that the problem in the question was caused by something other than what the asker thought, retagging is very helpful." from meta.stackoverflow.com/questions/252079/… applies here.
– Martin R
Jul 13 '17 at 14:13
1
@MartinR I don't know how questions can be updated to show that there are answers that apply to a current version of Swift; there is a lot of old, useless stuff here and [swift] finds it all along with the useful. I don't feel strongly about this retag being reverted but I wish there was a definitive way to solve this problem. (I wish answers had tags.)
– Adam Eberbach
Jul 14 '17 at 0:50
add a comment |
I have been working to create a UIAlertView in Swift, but for some reason I can't get the statement right because I'm getting this error:
Could not find an overload for 'init' that accepts the supplied
arguments
Here is how I have it written:
let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
Then to call it I'm using:
button2Alert.show()
As of right now it is crashing and I just can't seem to get the syntax right.
ios swift cocoa-touch uialertview uialertcontroller
I have been working to create a UIAlertView in Swift, but for some reason I can't get the statement right because I'm getting this error:
Could not find an overload for 'init' that accepts the supplied
arguments
Here is how I have it written:
let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
Then to call it I'm using:
button2Alert.show()
As of right now it is crashing and I just can't seem to get the syntax right.
ios swift cocoa-touch uialertview uialertcontroller
ios swift cocoa-touch uialertview uialertcontroller
edited Mar 26 '18 at 2:50
Dmitry
6,9221875152
6,9221875152
asked Jun 3 '14 at 18:35
BlueBearBlueBear
3,28952643
3,28952643
5
UIAlertView
andUIActionSheet
has been replaced byUIAlertController
in iOS 8, have you looked at this?
– Popeye
Jun 3 '14 at 18:51
Make sure the class thatself
belongs to adopts the protocolUIAlertViewDelegate
(the recommended way to do this, in Swift, is with an extension).
– Nicolas Miari
Jul 14 '15 at 7:37
@Adam: I have reverted your retagging. The swift3 tag is for "questions directly related to changes in version 3 of Apple's Swift programming language." And I don't think that "If the answers make it clear that the problem in the question was caused by something other than what the asker thought, retagging is very helpful." from meta.stackoverflow.com/questions/252079/… applies here.
– Martin R
Jul 13 '17 at 14:13
1
@MartinR I don't know how questions can be updated to show that there are answers that apply to a current version of Swift; there is a lot of old, useless stuff here and [swift] finds it all along with the useful. I don't feel strongly about this retag being reverted but I wish there was a definitive way to solve this problem. (I wish answers had tags.)
– Adam Eberbach
Jul 14 '17 at 0:50
add a comment |
5
UIAlertView
andUIActionSheet
has been replaced byUIAlertController
in iOS 8, have you looked at this?
– Popeye
Jun 3 '14 at 18:51
Make sure the class thatself
belongs to adopts the protocolUIAlertViewDelegate
(the recommended way to do this, in Swift, is with an extension).
– Nicolas Miari
Jul 14 '15 at 7:37
@Adam: I have reverted your retagging. The swift3 tag is for "questions directly related to changes in version 3 of Apple's Swift programming language." And I don't think that "If the answers make it clear that the problem in the question was caused by something other than what the asker thought, retagging is very helpful." from meta.stackoverflow.com/questions/252079/… applies here.
– Martin R
Jul 13 '17 at 14:13
1
@MartinR I don't know how questions can be updated to show that there are answers that apply to a current version of Swift; there is a lot of old, useless stuff here and [swift] finds it all along with the useful. I don't feel strongly about this retag being reverted but I wish there was a definitive way to solve this problem. (I wish answers had tags.)
– Adam Eberbach
Jul 14 '17 at 0:50
5
5
UIAlertView
and UIActionSheet
has been replaced by UIAlertController
in iOS 8, have you looked at this?– Popeye
Jun 3 '14 at 18:51
UIAlertView
and UIActionSheet
has been replaced by UIAlertController
in iOS 8, have you looked at this?– Popeye
Jun 3 '14 at 18:51
Make sure the class that
self
belongs to adopts the protocol UIAlertViewDelegate
(the recommended way to do this, in Swift, is with an extension).– Nicolas Miari
Jul 14 '15 at 7:37
Make sure the class that
self
belongs to adopts the protocol UIAlertViewDelegate
(the recommended way to do this, in Swift, is with an extension).– Nicolas Miari
Jul 14 '15 at 7:37
@Adam: I have reverted your retagging. The swift3 tag is for "questions directly related to changes in version 3 of Apple's Swift programming language." And I don't think that "If the answers make it clear that the problem in the question was caused by something other than what the asker thought, retagging is very helpful." from meta.stackoverflow.com/questions/252079/… applies here.
– Martin R
Jul 13 '17 at 14:13
@Adam: I have reverted your retagging. The swift3 tag is for "questions directly related to changes in version 3 of Apple's Swift programming language." And I don't think that "If the answers make it clear that the problem in the question was caused by something other than what the asker thought, retagging is very helpful." from meta.stackoverflow.com/questions/252079/… applies here.
– Martin R
Jul 13 '17 at 14:13
1
1
@MartinR I don't know how questions can be updated to show that there are answers that apply to a current version of Swift; there is a lot of old, useless stuff here and [swift] finds it all along with the useful. I don't feel strongly about this retag being reverted but I wish there was a definitive way to solve this problem. (I wish answers had tags.)
– Adam Eberbach
Jul 14 '17 at 0:50
@MartinR I don't know how questions can be updated to show that there are answers that apply to a current version of Swift; there is a lot of old, useless stuff here and [swift] finds it all along with the useful. I don't feel strongly about this retag being reverted but I wish there was a definitive way to solve this problem. (I wish answers had tags.)
– Adam Eberbach
Jul 14 '17 at 0:50
add a comment |
31 Answers
31
active
oldest
votes
1 2
next
From the UIAlertView
class:
// UIAlertView is deprecated. Use UIAlertController with a
preferredStyle of UIAlertControllerStyleAlert instead
On iOS 8, you can do this:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Now UIAlertController
is a single class for creating and interacting with what we knew as UIAlertView
s and UIActionSheet
s on iOS 8.
Edit: To handle actions:
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
switch action.style{
case .Default:
print("default")
case .Cancel:
print("cancel")
case .Destructive:
print("destructive")
}
}}))
Edit for Swift 3:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
Edit for Swift 4.x:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}}))
self.present(alert, animated: true, completion: nil)
3
Where did you see that UIAlertView is deprecated? I don't see that in the documentation?
– BlueBear
Jun 3 '14 at 18:58
8
Cmd + Click theUIAlertView
class, and the comment is right on top of the class declaration.
– Oscar Swanros
Jun 3 '14 at 19:00
2
I'll answer my own question for anyone else who's curious alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (ACTION :UIAlertAction!)in }))
– altyus
Jun 3 '14 at 20:27
5
What's the point of Cancel and Destructive cases since it will always be what you specified.Default
?
– User
Sep 21 '14 at 3:42
3
Reading this answer the switch case you did is unnecessary. The switch is only useful if the type, or title aren't hardcoded ie they are dynamic: You might have a series of dynamic buttons so the titles are not hardcoded. And then the handler might need to pass the chosen title off to some other method call
– Honey
Nov 30 '16 at 17:27
|
show 4 more comments
One Button
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Two Buttons
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "UIAlertController", message: "Would you like to continue learning how to use iOS alerts?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Three Buttons
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "Notice", message: "Lauching this missile will destroy the entire universe. Is this what you intended to do?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Remind Me Tomorrow", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActio.nStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Handling Button Taps
The handler
was nil
in the above examples. You can replace nil
with a closure to do something when the user taps a button. For example:
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: { action in
// do something like...
self.launchMissile()
}))
Notes
- Multiple buttons do not necessarily need to use different
UIAlertAction.Style
types. They could all be.default
. - For more than three buttons consider using an Action Sheet. The setup is very similar. Here is an example.
2
is there any delegate property in UIAlertController? in UIAlertView there is a delegate property which we sometime set to self, Is there any nothing like this in UIAlertController?? I am New , please help me
– ArgaPK
Nov 1 '17 at 6:03
add a comment |
You can create a UIAlert using the standard constructor, but the 'legacy' one seems to not work:
let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
8
UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.
– Zorayr
Jan 12 '15 at 3:00
15
@Zorayr UIAlertController is only available from iOS 8 onwards, please also mention that when suggesting its use. There are situations where iOS7 support is still desired and people might miss the problem. Deprecation doesn't mean "don't ever use this anymore."
– Sami Kuhmonen
Apr 2 '15 at 7:38
2
This works if your app is still targeting iOS 7. However, ideally UIAlertView should only be used when UIAlertController is not available. if NSClassFromString("UIAlertController") != nil { /* use UIAlertController * / } else { /* use UIAlertView * / }
– phatblat
Apr 16 '15 at 17:01
UIAlertview() is now deprecated in iOS 9
– Rizwan Ahmed
Sep 27 '15 at 7:33
add a comment |
Click of View
@IBAction func testClick(sender: UIButton) {
var uiAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(uiAlert, animated: true, completion: nil)
uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
println("Click of default button")
}))
uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
println("Click of cancel button")
}))
}
Done with two buttons OK & Cancel
add a comment |
In Swift 4.2 and Xcode 10
Method 1 :
SIMPLE ALERT
let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(ok)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
Method 2 :
ALERT WITH SHARED CLASS
If you want Shared class style(Write once use every where)
import UIKit
class SharedClass: NSObject {//This is shared class
static let sharedInstance = SharedClass()
//Show alert
func alert(view: UIViewController, title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(defaultAction)
DispatchQueue.main.async(execute: {
view.present(alert, animated: true)
})
}
private override init() {
}
}
Now call alert like this in every ware
SharedClass.SharedInstance.alert(view: self, title: "Your title here", message: "Your message here")
Method 3 :
PRESENT ALERT TOP OF ALL WINDOWS
If you want to present alert on top of all views, use this code
func alertWindow(title: String, message: String) {
DispatchQueue.main.async(execute: {
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1
let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert2.addAction(defaultAction2)
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
})
}
Function calling
SharedClass.sharedInstance.alertWindow(title:"This your title", message:"This is your message")
Method 4 :
Alert with Extension
extension UIViewController {
func showAlert(withTitle title: String, withMessage message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(ok)
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
}
}
Now call like this
//Call showAlert function in your class
@IBAction func onClickAlert(_ sender: UIButton) {
showAlert(withTitle:"Your Title Here", withMessage: "YourCustomMessageHere")
}
Method 5 :
ALERT WITH TEXTFIELDS
If you want to add textfields to alert.
//Global variables
var name:String?
var login:String?
//Call this function like this: alertWithTF()
//Add textfields to alert
func alertWithTF() {
let alert = UIAlertController(title: "Login", message: "Enter username&password", preferredStyle: .alert)
// Login button
let loginAction = UIAlertAction(title: "Login", style: .default, handler: { (action) -> Void in
// Get TextFields text
let usernameTxt = alert.textFields![0]
let passwordTxt = alert.textFields![1]
//Asign textfileds text to our global varibles
self.name = usernameTxt.text
self.login = passwordTxt.text
print("USERNAME: (self.name!)nPASSWORD: (self.login!)")
})
// Cancel button
let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in })
//1 textField for username
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter username"
//If required mention keyboard type, delegates, text sixe and font etc...
//EX:
textField.keyboardType = .default
}
//2nd textField for password
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter password"
textField.isSecureTextEntry = true
}
// Add actions
alert.addAction(loginAction)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
add a comment |
If you're targeting iOS 7 and 8, you need something like this to make sure you're using the right method for each version, because UIAlertView
is deprecated in iOS 8, but UIAlertController
is not available in iOS 7:
func alert(title: String, message: String) {
if let getModernAlert: AnyClass = NSClassFromString("UIAlertController") { // iOS 8
let myAlert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
myAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(myAlert, animated: true, completion: nil)
} else { // iOS 7
let alert: UIAlertView = UIAlertView()
alert.delegate = self
alert.title = title
alert.message = message
alert.addButtonWithTitle("OK")
alert.show()
}
}
Or you can save time and just useUIAlertView
until you drop support for iOS 7. Apple won't reject your app for that.
– cprcrack
Jan 19 '15 at 16:17
2
Deprecation doesn't mean "don't use this" or that it would be the "wrong method", it just means it will not work later on. There's no need to specifically use UIAlertController on iOS8 if one just needs basic alerts. They will work as before. There are many APIs that have been deprecated in iOS4 or 5 and still work in iOS8. But of course apps targeting a higher iOS level should not use them and that's why there is a deprecation warning.
– Sami Kuhmonen
Apr 2 '15 at 7:47
1
@SamiKuhmonen No, but it makes it clearer why you're doing what you're doing and makes it easier to remove support for deprecated methods when your minimum version is high enough to do so.
– AstroCB
Apr 2 '15 at 10:17
add a comment |
Show UIAlertView in swift language :-
Protocol UIAlertViewDelegate
let alert = UIAlertView(title: "alertView", message: "This is alertView", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles: "Done", "Delete")
alert.show()
Show UIAlertViewController in swift language :-
let alert = UIAlertController(title: "Error", message: "Enter data in Text fields", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
This answers the question directly and is correct
– Fraser
Aug 19 '15 at 1:29
add a comment |
Simply do not provide otherButtonTitles in the constructor.
let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
But I do agree with Oscar, this class is deprecated in iOS 8, so there won't be no use of UIAlertView if you're doing an iOS 8 only app. Otherwise the code above will work.
add a comment |
With the protocol extensions of Swift 2, you can make a protocol that provides a default implementation to your view controllers:
ShowsAlert.swift
import UIKit
protocol ShowsAlert {}
extension ShowsAlert where Self: UIViewController {
func showAlert(title: String = "Error", message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
}
}
ViewController.swift
class ViewController: UIViewController, ShowsAlert {
override func viewDidLoad() {
super.viewDidLoad()
showAlert(message: "Hey there, I am an error message!")
}
}
1
Works perfectly. For Swift3 change 'presentViewController' to 'present'.
– Vincent
Jan 18 '17 at 8:38
add a comment |
I found this one,
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
not good though, but it works :)
Update:
but I have found on header file as:
extension UIAlertView {
convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}
somebody may can explain this.
Apparently UIAlertView has been deprecated in iOS 8 and we now use UIAlertController with a preferred style of UIAlertControllerStyleAlert.
– BlueBear
Jun 3 '14 at 19:06
6
If you run an app that needs to be backwards compatible to iOS7.1 and you're writing it in Swift, the UIAlertController will crash the target device. You need to support the legacy UIAlertViews for iOS7.
– Joe
Jun 22 '14 at 4:02
I think that it's not Swift that would cause a crash, but rather the fact that the UIAlertController is not available before iOS 8
– Frédéric Adda
Aug 24 '14 at 20:12
add a comment |
For SWIFT4, I think, extending UIViewController
and creating a reusable confirmation control is the most elegant way.
You can extend the UIViewController
as below:
extension UIViewController {
func AskConfirmation (title:String, message:String, completion:@escaping (_ result:Bool) -> Void) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
completion(true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
completion(false)
}))
}
}
Then you can use it anytime:
AskConfirmation(title: "YOUR MESSAGE TITLE", message: "YOUR MESSAGE") { (result) in
if result { //User has clicked on Ok
} else { //User has clicked on Cancel
}
}
add a comment |
class Preview: UIViewController , UIAlertViewDelegate
{
@IBAction func MoreBtnClicked(sender: AnyObject)
{
var moreAlert=UIAlertView(title: "Photo", message: "", delegate: self, cancelButtonTitle: "No Thanks!", otherButtonTitles: "Save Image", "Email", "Facebook", "Whatsapp" )
moreAlert.show()
moreAlert.tag=111;
}
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int)
{
if alertView.tag==111
{
if buttonIndex==0
{
println("No Thanks!")
}
else if buttonIndex==1
{
println("Save Image")
}
else if buttonIndex == 2
{
println("Email")
}
else if buttonIndex == 3
{
println("Facebook")
}
else if buttonIndex == 4
{
println("Whatsapp")
}
}
}
}
Just writing a lump of code is not very useful. When answering any question (specially an old question with several answers including an accepted answer) please write more than a piece of code. Please add an explanation of what your code does, how it answers the question and how it is different (or better) than the other answers.
– AdrianHHH
Jul 10 '15 at 13:00
Fantastic answer, Jayesh, thanks for that.
– Fattie
Dec 15 '16 at 23:37
add a comment |
I have another trick. Suppose you have 5 classes where a logout alert to be applied. Try with swift class extension.
File- New- Swift class- Name it.
Add the following:
public extension UIViewController
{
func makeLogOutAlert()
{
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
self.navigationController?.popToRootViewControllerAnimated(true)
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
refreshAlert .dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(refreshAlert, animated: true, completion: nil)
}
}
Implement using : self.makeLogOutAlert(). Hope it helps.
add a comment |
I have made a singleton class to make this convenient to use from anywhere in your app: https://github.com/Swinny1989/Swift-Popups
You can then create a popup with multiple buttons like this:
Popups.SharedInstance.ShowAlert(self, title: "Title goes here", message: "Messages goes here", buttons: ["button one" , "button two"]) { (buttonPressed) -> Void in
if buttonPressed == "button one" {
//Code here
} else if buttonPressed == "button two" {
// Code here
}
}
or popups with a single button like this:
Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")
Thanks. I submit some issue there
– djdance
Jan 7 '16 at 19:32
1
Hey @Swinny89 Thanks so much man for sharing this solution with us! I got stuck with the closure thing and you just saved me!
– Bruno Campos
Mar 29 '18 at 17:15
add a comment |
Swift 3
The following is a simple example of how to create a simple alert with one button with Swift 3.
let alert = UIAlertController(title: "Title",
message: "Message",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)
In the above example the handle callback of the action has been omitted because the default behaviour of an alert view with one button is to disappear when the button is clicked.
Here is how to create another action, which could be added to the alert with "alert.addAction(action)". The different styles are .default, .destructive and .cancel.
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
}
add a comment |
I got the following UIAlertView
initialization code to compile without errors (I thing the last, varyadic part is tricky perhaps). But I had to make sure the class of self
(which I am passing as the delegate) was adopting the UIAlertViewDelegate
protocol for the compile errors to go away:
let alertView = UIAlertView(
title: "My Title",
message: "My Message",
delegate: self,
cancelButtonTitle: "Cancel",
otherButtonTitles: "OK"
)
By the way, this is the error I was getting (as of Xcode 6.4):
Cannot find an initializer for type 'UIAlertView' that accepts an
argument list of type '(title: String, message: String, delegate:
MyViewController, cancelButtonTitle: String, otherButtonTitles:
String)'
As others mentioned, you should migrate to UIAlertController if you can target iOS 8.x+. To support iOS 7, use the code above (iOS 6 is not supported by Swift).
add a comment |
The reason it doesn't work because some value you passed to the function isn't correct. swift doesn't like Objective-C, you can put nil to arguments which are class type without any restriction(might be). Argument otherButtonTitles is defined as non-optional which its type do not have (?)at its end. so you must pass a concrete value to it.
add a comment |
@IBAction func Alert(sender: UIButton) {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Alert!"
alertView.message = "Message"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
Try this
add a comment |
Use this code to display an alertview
let alertController = UIAlertController(title: "Hello Coders", message: "your alert message", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
Reference: Swift Show Alert using UIAlertController
add a comment |
in xcode 9
let alert = UIAlertController(title: "Alert", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
add a comment |
let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .alert)
let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
print("Default is pressed.....")
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancel is pressed......")
}
let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
print("Destructive is pressed....")
}
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
add a comment |
SWIFT 4 : Simply create a extension to UIViewController as follows:
extension UIViewController {
func showSuccessAlert(withTitle title: String, andMessage message:String) {
let alert = UIAlertController(title: title, message: message,
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK".localized, style:
UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Now in your ViewController, directly call above function as if they are provided by UIViewController.
yourViewController.showSuccessAlert(withTitle:
"YourTitle", andMessage: "YourCustomTitle")
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. Thanks for improving the answer's reference value and making it more understandable!
– Tim Diekmann
Jun 3 '18 at 13:58
add a comment |
try This.
Put Bellow Code In Button.
let alert = UIAlertController(title: "Your_Title_Text", message: "Your_MSG", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Your_Text", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated:true, completion: nil)
add a comment |
SWIFT 4.X
let alert = UIAlertController(title: "user entered title", message: "user entered message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
print("Okay'd")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { action in
print("cancelled")
}))
self.present(alert, animated: true, completion: nil)
Added this to response to show how to do multiple actions (ie. OK / Cancel)
– Stotch
Jan 14 at 0:09
1
Don't post duplicate answers, please remove it...
– iOS
Jan 28 at 9:59
@Stotch Please don't post duplicate answer's, this answer already available in this question. Please post some different answer only not same type of answer. Please remove your answer....
– Marking
Jan 30 at 9:56
add a comment |
Here is a funny example in Swift:
private func presentRandomJoke() {
if let randomJoke: String = jokesController.randomJoke() {
let alertController: UIAlertController = UIAlertController(title:nil, message:randomJoke, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title:"Done", style:UIAlertActionStyle.Default, handler:nil))
presentViewController(alertController, animated:true, completion:nil)
}
}
add a comment |
Here is a pretty simple function of AlertView in Swift :
class func globalAlertYesNo(msg: String) {
let alertView = UNAlertView(title: "Title", message: msg)
alertView.messageAlignment = NSTextAlignment.Center
alertView.buttonAlignment = UNButtonAlignment.Horizontal
alertView.addButton("Yes", action: {
print("Yes action")
})
alertView.addButton("No", action: {
print("No action")
})
alertView.show()
}
You have to pass message as a String where you use this function.
add a comment |
The Old Way: UIAlertView
let alertView = UIAlertView(title: "Default Style", message: "A standard alert.", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alertView.alertViewStyle = .Default
alertView.show()
// MARK: UIAlertViewDelegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
// ...
}
}
The New Way: UIAlertController
let alertController = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
add a comment |
on IOS 9, you can do this
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
add a comment |
// Generic Class For UIAlertView
//MARK:- MODULES
import Foundation
import UIKit
//MARK:- CLASS
class Alert : NSObject{
static let shared = Alert()
var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?
/** show */
public func show(title : String?, message : String?, viewController : UIViewController?, okAction : AlertSuccess = nil) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil);
}
}
/** showWithCancelAndOk */
public func showWithCancelAndOk(title : String, okTitle : String, cancelTitle : String, message : String, viewController : UIViewController?, okAction : AlertSuccess = nil, cancelAction : AlertSuccess = nil) {
let version:NSString = UIDevice.current.systemVersion as NSString;
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: cancelTitle, style: .default, handler: { (action: UIAlertAction) in
if let cancelAction = cancelAction {
cancelAction()
}
}))
alert?.addAction(UIAlertAction(title: okTitle, style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert!, animated:true, completion:nil);
}
}
/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when){
self.alert?.dismiss(animated: true, completion: nil)
}
}
}
}
Use:-
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self) //without ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}) // with ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}, cancelAction: {
//cancel action
}) //with cancel and ok action
Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self) //with timer
add a comment |
// UIAlertView is deprecated. Use UIAlertController
// title = title of the alert view.
// message = Alert message you want to show.
// By tap on "OK" , Alert view will dismiss.
UIAlertView(title: "Alert", message: "Enter Message here.", delegate: nil, cancelButtonTitle: "OK").show()
Can you please add an explanation to the code you posted? As it is now, your answer does not really qualify as a good answer by SO rules.
– Nico Van Belle
May 4 '18 at 7:42
alert view has changed now in swift 4.use alert controller
– Sandeep Singh
May 15 '18 at 7:54
add a comment |
1 2
next
protected by Nilesh Rathod Apr 18 '18 at 5:00
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
31 Answers
31
active
oldest
votes
31 Answers
31
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
From the UIAlertView
class:
// UIAlertView is deprecated. Use UIAlertController with a
preferredStyle of UIAlertControllerStyleAlert instead
On iOS 8, you can do this:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Now UIAlertController
is a single class for creating and interacting with what we knew as UIAlertView
s and UIActionSheet
s on iOS 8.
Edit: To handle actions:
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
switch action.style{
case .Default:
print("default")
case .Cancel:
print("cancel")
case .Destructive:
print("destructive")
}
}}))
Edit for Swift 3:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
Edit for Swift 4.x:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}}))
self.present(alert, animated: true, completion: nil)
3
Where did you see that UIAlertView is deprecated? I don't see that in the documentation?
– BlueBear
Jun 3 '14 at 18:58
8
Cmd + Click theUIAlertView
class, and the comment is right on top of the class declaration.
– Oscar Swanros
Jun 3 '14 at 19:00
2
I'll answer my own question for anyone else who's curious alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (ACTION :UIAlertAction!)in }))
– altyus
Jun 3 '14 at 20:27
5
What's the point of Cancel and Destructive cases since it will always be what you specified.Default
?
– User
Sep 21 '14 at 3:42
3
Reading this answer the switch case you did is unnecessary. The switch is only useful if the type, or title aren't hardcoded ie they are dynamic: You might have a series of dynamic buttons so the titles are not hardcoded. And then the handler might need to pass the chosen title off to some other method call
– Honey
Nov 30 '16 at 17:27
|
show 4 more comments
From the UIAlertView
class:
// UIAlertView is deprecated. Use UIAlertController with a
preferredStyle of UIAlertControllerStyleAlert instead
On iOS 8, you can do this:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Now UIAlertController
is a single class for creating and interacting with what we knew as UIAlertView
s and UIActionSheet
s on iOS 8.
Edit: To handle actions:
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
switch action.style{
case .Default:
print("default")
case .Cancel:
print("cancel")
case .Destructive:
print("destructive")
}
}}))
Edit for Swift 3:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
Edit for Swift 4.x:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}}))
self.present(alert, animated: true, completion: nil)
3
Where did you see that UIAlertView is deprecated? I don't see that in the documentation?
– BlueBear
Jun 3 '14 at 18:58
8
Cmd + Click theUIAlertView
class, and the comment is right on top of the class declaration.
– Oscar Swanros
Jun 3 '14 at 19:00
2
I'll answer my own question for anyone else who's curious alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (ACTION :UIAlertAction!)in }))
– altyus
Jun 3 '14 at 20:27
5
What's the point of Cancel and Destructive cases since it will always be what you specified.Default
?
– User
Sep 21 '14 at 3:42
3
Reading this answer the switch case you did is unnecessary. The switch is only useful if the type, or title aren't hardcoded ie they are dynamic: You might have a series of dynamic buttons so the titles are not hardcoded. And then the handler might need to pass the chosen title off to some other method call
– Honey
Nov 30 '16 at 17:27
|
show 4 more comments
From the UIAlertView
class:
// UIAlertView is deprecated. Use UIAlertController with a
preferredStyle of UIAlertControllerStyleAlert instead
On iOS 8, you can do this:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Now UIAlertController
is a single class for creating and interacting with what we knew as UIAlertView
s and UIActionSheet
s on iOS 8.
Edit: To handle actions:
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
switch action.style{
case .Default:
print("default")
case .Cancel:
print("cancel")
case .Destructive:
print("destructive")
}
}}))
Edit for Swift 3:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
Edit for Swift 4.x:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}}))
self.present(alert, animated: true, completion: nil)
From the UIAlertView
class:
// UIAlertView is deprecated. Use UIAlertController with a
preferredStyle of UIAlertControllerStyleAlert instead
On iOS 8, you can do this:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Now UIAlertController
is a single class for creating and interacting with what we knew as UIAlertView
s and UIActionSheet
s on iOS 8.
Edit: To handle actions:
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
switch action.style{
case .Default:
print("default")
case .Cancel:
print("cancel")
case .Destructive:
print("destructive")
}
}}))
Edit for Swift 3:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
Edit for Swift 4.x:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}}))
self.present(alert, animated: true, completion: nil)
edited Nov 20 '18 at 13:57
iHarshil
144313
144313
answered Jun 3 '14 at 18:48
Oscar SwanrosOscar Swanros
16.7k52847
16.7k52847
3
Where did you see that UIAlertView is deprecated? I don't see that in the documentation?
– BlueBear
Jun 3 '14 at 18:58
8
Cmd + Click theUIAlertView
class, and the comment is right on top of the class declaration.
– Oscar Swanros
Jun 3 '14 at 19:00
2
I'll answer my own question for anyone else who's curious alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (ACTION :UIAlertAction!)in }))
– altyus
Jun 3 '14 at 20:27
5
What's the point of Cancel and Destructive cases since it will always be what you specified.Default
?
– User
Sep 21 '14 at 3:42
3
Reading this answer the switch case you did is unnecessary. The switch is only useful if the type, or title aren't hardcoded ie they are dynamic: You might have a series of dynamic buttons so the titles are not hardcoded. And then the handler might need to pass the chosen title off to some other method call
– Honey
Nov 30 '16 at 17:27
|
show 4 more comments
3
Where did you see that UIAlertView is deprecated? I don't see that in the documentation?
– BlueBear
Jun 3 '14 at 18:58
8
Cmd + Click theUIAlertView
class, and the comment is right on top of the class declaration.
– Oscar Swanros
Jun 3 '14 at 19:00
2
I'll answer my own question for anyone else who's curious alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (ACTION :UIAlertAction!)in }))
– altyus
Jun 3 '14 at 20:27
5
What's the point of Cancel and Destructive cases since it will always be what you specified.Default
?
– User
Sep 21 '14 at 3:42
3
Reading this answer the switch case you did is unnecessary. The switch is only useful if the type, or title aren't hardcoded ie they are dynamic: You might have a series of dynamic buttons so the titles are not hardcoded. And then the handler might need to pass the chosen title off to some other method call
– Honey
Nov 30 '16 at 17:27
3
3
Where did you see that UIAlertView is deprecated? I don't see that in the documentation?
– BlueBear
Jun 3 '14 at 18:58
Where did you see that UIAlertView is deprecated? I don't see that in the documentation?
– BlueBear
Jun 3 '14 at 18:58
8
8
Cmd + Click the
UIAlertView
class, and the comment is right on top of the class declaration.– Oscar Swanros
Jun 3 '14 at 19:00
Cmd + Click the
UIAlertView
class, and the comment is right on top of the class declaration.– Oscar Swanros
Jun 3 '14 at 19:00
2
2
I'll answer my own question for anyone else who's curious alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (ACTION :UIAlertAction!)in }))
– altyus
Jun 3 '14 at 20:27
I'll answer my own question for anyone else who's curious alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (ACTION :UIAlertAction!)in }))
– altyus
Jun 3 '14 at 20:27
5
5
What's the point of Cancel and Destructive cases since it will always be what you specified
.Default
?– User
Sep 21 '14 at 3:42
What's the point of Cancel and Destructive cases since it will always be what you specified
.Default
?– User
Sep 21 '14 at 3:42
3
3
Reading this answer the switch case you did is unnecessary. The switch is only useful if the type, or title aren't hardcoded ie they are dynamic: You might have a series of dynamic buttons so the titles are not hardcoded. And then the handler might need to pass the chosen title off to some other method call
– Honey
Nov 30 '16 at 17:27
Reading this answer the switch case you did is unnecessary. The switch is only useful if the type, or title aren't hardcoded ie they are dynamic: You might have a series of dynamic buttons so the titles are not hardcoded. And then the handler might need to pass the chosen title off to some other method call
– Honey
Nov 30 '16 at 17:27
|
show 4 more comments
One Button
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Two Buttons
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "UIAlertController", message: "Would you like to continue learning how to use iOS alerts?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Three Buttons
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "Notice", message: "Lauching this missile will destroy the entire universe. Is this what you intended to do?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Remind Me Tomorrow", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActio.nStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Handling Button Taps
The handler
was nil
in the above examples. You can replace nil
with a closure to do something when the user taps a button. For example:
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: { action in
// do something like...
self.launchMissile()
}))
Notes
- Multiple buttons do not necessarily need to use different
UIAlertAction.Style
types. They could all be.default
. - For more than three buttons consider using an Action Sheet. The setup is very similar. Here is an example.
2
is there any delegate property in UIAlertController? in UIAlertView there is a delegate property which we sometime set to self, Is there any nothing like this in UIAlertController?? I am New , please help me
– ArgaPK
Nov 1 '17 at 6:03
add a comment |
One Button
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Two Buttons
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "UIAlertController", message: "Would you like to continue learning how to use iOS alerts?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Three Buttons
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "Notice", message: "Lauching this missile will destroy the entire universe. Is this what you intended to do?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Remind Me Tomorrow", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActio.nStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Handling Button Taps
The handler
was nil
in the above examples. You can replace nil
with a closure to do something when the user taps a button. For example:
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: { action in
// do something like...
self.launchMissile()
}))
Notes
- Multiple buttons do not necessarily need to use different
UIAlertAction.Style
types. They could all be.default
. - For more than three buttons consider using an Action Sheet. The setup is very similar. Here is an example.
2
is there any delegate property in UIAlertController? in UIAlertView there is a delegate property which we sometime set to self, Is there any nothing like this in UIAlertController?? I am New , please help me
– ArgaPK
Nov 1 '17 at 6:03
add a comment |
One Button
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Two Buttons
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "UIAlertController", message: "Would you like to continue learning how to use iOS alerts?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Three Buttons
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "Notice", message: "Lauching this missile will destroy the entire universe. Is this what you intended to do?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Remind Me Tomorrow", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActio.nStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Handling Button Taps
The handler
was nil
in the above examples. You can replace nil
with a closure to do something when the user taps a button. For example:
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: { action in
// do something like...
self.launchMissile()
}))
Notes
- Multiple buttons do not necessarily need to use different
UIAlertAction.Style
types. They could all be.default
. - For more than three buttons consider using an Action Sheet. The setup is very similar. Here is an example.
One Button
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Two Buttons
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "UIAlertController", message: "Would you like to continue learning how to use iOS alerts?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Three Buttons
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "Notice", message: "Lauching this missile will destroy the entire universe. Is this what you intended to do?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Remind Me Tomorrow", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActio.nStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Handling Button Taps
The handler
was nil
in the above examples. You can replace nil
with a closure to do something when the user taps a button. For example:
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: { action in
// do something like...
self.launchMissile()
}))
Notes
- Multiple buttons do not necessarily need to use different
UIAlertAction.Style
types. They could all be.default
. - For more than three buttons consider using an Action Sheet. The setup is very similar. Here is an example.
edited Oct 5 '18 at 14:18
answered Oct 26 '15 at 7:44
SuragchSuragch
209k124701764
209k124701764
2
is there any delegate property in UIAlertController? in UIAlertView there is a delegate property which we sometime set to self, Is there any nothing like this in UIAlertController?? I am New , please help me
– ArgaPK
Nov 1 '17 at 6:03
add a comment |
2
is there any delegate property in UIAlertController? in UIAlertView there is a delegate property which we sometime set to self, Is there any nothing like this in UIAlertController?? I am New , please help me
– ArgaPK
Nov 1 '17 at 6:03
2
2
is there any delegate property in UIAlertController? in UIAlertView there is a delegate property which we sometime set to self, Is there any nothing like this in UIAlertController?? I am New , please help me
– ArgaPK
Nov 1 '17 at 6:03
is there any delegate property in UIAlertController? in UIAlertView there is a delegate property which we sometime set to self, Is there any nothing like this in UIAlertController?? I am New , please help me
– ArgaPK
Nov 1 '17 at 6:03
add a comment |
You can create a UIAlert using the standard constructor, but the 'legacy' one seems to not work:
let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
8
UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.
– Zorayr
Jan 12 '15 at 3:00
15
@Zorayr UIAlertController is only available from iOS 8 onwards, please also mention that when suggesting its use. There are situations where iOS7 support is still desired and people might miss the problem. Deprecation doesn't mean "don't ever use this anymore."
– Sami Kuhmonen
Apr 2 '15 at 7:38
2
This works if your app is still targeting iOS 7. However, ideally UIAlertView should only be used when UIAlertController is not available. if NSClassFromString("UIAlertController") != nil { /* use UIAlertController * / } else { /* use UIAlertView * / }
– phatblat
Apr 16 '15 at 17:01
UIAlertview() is now deprecated in iOS 9
– Rizwan Ahmed
Sep 27 '15 at 7:33
add a comment |
You can create a UIAlert using the standard constructor, but the 'legacy' one seems to not work:
let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
8
UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.
– Zorayr
Jan 12 '15 at 3:00
15
@Zorayr UIAlertController is only available from iOS 8 onwards, please also mention that when suggesting its use. There are situations where iOS7 support is still desired and people might miss the problem. Deprecation doesn't mean "don't ever use this anymore."
– Sami Kuhmonen
Apr 2 '15 at 7:38
2
This works if your app is still targeting iOS 7. However, ideally UIAlertView should only be used when UIAlertController is not available. if NSClassFromString("UIAlertController") != nil { /* use UIAlertController * / } else { /* use UIAlertView * / }
– phatblat
Apr 16 '15 at 17:01
UIAlertview() is now deprecated in iOS 9
– Rizwan Ahmed
Sep 27 '15 at 7:33
add a comment |
You can create a UIAlert using the standard constructor, but the 'legacy' one seems to not work:
let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
You can create a UIAlert using the standard constructor, but the 'legacy' one seems to not work:
let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
edited Mar 29 '17 at 13:47
Benjamin Gruenbaum
190k63403440
190k63403440
answered Jun 3 '14 at 18:52
Ben GottliebBen Gottlieb
79.6k22168169
79.6k22168169
8
UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.
– Zorayr
Jan 12 '15 at 3:00
15
@Zorayr UIAlertController is only available from iOS 8 onwards, please also mention that when suggesting its use. There are situations where iOS7 support is still desired and people might miss the problem. Deprecation doesn't mean "don't ever use this anymore."
– Sami Kuhmonen
Apr 2 '15 at 7:38
2
This works if your app is still targeting iOS 7. However, ideally UIAlertView should only be used when UIAlertController is not available. if NSClassFromString("UIAlertController") != nil { /* use UIAlertController * / } else { /* use UIAlertView * / }
– phatblat
Apr 16 '15 at 17:01
UIAlertview() is now deprecated in iOS 9
– Rizwan Ahmed
Sep 27 '15 at 7:33
add a comment |
8
UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.
– Zorayr
Jan 12 '15 at 3:00
15
@Zorayr UIAlertController is only available from iOS 8 onwards, please also mention that when suggesting its use. There are situations where iOS7 support is still desired and people might miss the problem. Deprecation doesn't mean "don't ever use this anymore."
– Sami Kuhmonen
Apr 2 '15 at 7:38
2
This works if your app is still targeting iOS 7. However, ideally UIAlertView should only be used when UIAlertController is not available. if NSClassFromString("UIAlertController") != nil { /* use UIAlertController * / } else { /* use UIAlertView * / }
– phatblat
Apr 16 '15 at 17:01
UIAlertview() is now deprecated in iOS 9
– Rizwan Ahmed
Sep 27 '15 at 7:33
8
8
UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.
– Zorayr
Jan 12 '15 at 3:00
UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.
– Zorayr
Jan 12 '15 at 3:00
15
15
@Zorayr UIAlertController is only available from iOS 8 onwards, please also mention that when suggesting its use. There are situations where iOS7 support is still desired and people might miss the problem. Deprecation doesn't mean "don't ever use this anymore."
– Sami Kuhmonen
Apr 2 '15 at 7:38
@Zorayr UIAlertController is only available from iOS 8 onwards, please also mention that when suggesting its use. There are situations where iOS7 support is still desired and people might miss the problem. Deprecation doesn't mean "don't ever use this anymore."
– Sami Kuhmonen
Apr 2 '15 at 7:38
2
2
This works if your app is still targeting iOS 7. However, ideally UIAlertView should only be used when UIAlertController is not available. if NSClassFromString("UIAlertController") != nil { /* use UIAlertController * / } else { /* use UIAlertView * / }
– phatblat
Apr 16 '15 at 17:01
This works if your app is still targeting iOS 7. However, ideally UIAlertView should only be used when UIAlertController is not available. if NSClassFromString("UIAlertController") != nil { /* use UIAlertController * / } else { /* use UIAlertView * / }
– phatblat
Apr 16 '15 at 17:01
UIAlertview() is now deprecated in iOS 9
– Rizwan Ahmed
Sep 27 '15 at 7:33
UIAlertview() is now deprecated in iOS 9
– Rizwan Ahmed
Sep 27 '15 at 7:33
add a comment |
Click of View
@IBAction func testClick(sender: UIButton) {
var uiAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(uiAlert, animated: true, completion: nil)
uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
println("Click of default button")
}))
uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
println("Click of cancel button")
}))
}
Done with two buttons OK & Cancel
add a comment |
Click of View
@IBAction func testClick(sender: UIButton) {
var uiAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(uiAlert, animated: true, completion: nil)
uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
println("Click of default button")
}))
uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
println("Click of cancel button")
}))
}
Done with two buttons OK & Cancel
add a comment |
Click of View
@IBAction func testClick(sender: UIButton) {
var uiAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(uiAlert, animated: true, completion: nil)
uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
println("Click of default button")
}))
uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
println("Click of cancel button")
}))
}
Done with two buttons OK & Cancel
Click of View
@IBAction func testClick(sender: UIButton) {
var uiAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(uiAlert, animated: true, completion: nil)
uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
println("Click of default button")
}))
uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
println("Click of cancel button")
}))
}
Done with two buttons OK & Cancel
edited May 10 '15 at 16:21
answered May 10 '15 at 16:15
Hiren PatelHiren Patel
37.1k14138121
37.1k14138121
add a comment |
add a comment |
In Swift 4.2 and Xcode 10
Method 1 :
SIMPLE ALERT
let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(ok)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
Method 2 :
ALERT WITH SHARED CLASS
If you want Shared class style(Write once use every where)
import UIKit
class SharedClass: NSObject {//This is shared class
static let sharedInstance = SharedClass()
//Show alert
func alert(view: UIViewController, title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(defaultAction)
DispatchQueue.main.async(execute: {
view.present(alert, animated: true)
})
}
private override init() {
}
}
Now call alert like this in every ware
SharedClass.SharedInstance.alert(view: self, title: "Your title here", message: "Your message here")
Method 3 :
PRESENT ALERT TOP OF ALL WINDOWS
If you want to present alert on top of all views, use this code
func alertWindow(title: String, message: String) {
DispatchQueue.main.async(execute: {
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1
let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert2.addAction(defaultAction2)
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
})
}
Function calling
SharedClass.sharedInstance.alertWindow(title:"This your title", message:"This is your message")
Method 4 :
Alert with Extension
extension UIViewController {
func showAlert(withTitle title: String, withMessage message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(ok)
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
}
}
Now call like this
//Call showAlert function in your class
@IBAction func onClickAlert(_ sender: UIButton) {
showAlert(withTitle:"Your Title Here", withMessage: "YourCustomMessageHere")
}
Method 5 :
ALERT WITH TEXTFIELDS
If you want to add textfields to alert.
//Global variables
var name:String?
var login:String?
//Call this function like this: alertWithTF()
//Add textfields to alert
func alertWithTF() {
let alert = UIAlertController(title: "Login", message: "Enter username&password", preferredStyle: .alert)
// Login button
let loginAction = UIAlertAction(title: "Login", style: .default, handler: { (action) -> Void in
// Get TextFields text
let usernameTxt = alert.textFields![0]
let passwordTxt = alert.textFields![1]
//Asign textfileds text to our global varibles
self.name = usernameTxt.text
self.login = passwordTxt.text
print("USERNAME: (self.name!)nPASSWORD: (self.login!)")
})
// Cancel button
let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in })
//1 textField for username
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter username"
//If required mention keyboard type, delegates, text sixe and font etc...
//EX:
textField.keyboardType = .default
}
//2nd textField for password
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter password"
textField.isSecureTextEntry = true
}
// Add actions
alert.addAction(loginAction)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
add a comment |
In Swift 4.2 and Xcode 10
Method 1 :
SIMPLE ALERT
let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(ok)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
Method 2 :
ALERT WITH SHARED CLASS
If you want Shared class style(Write once use every where)
import UIKit
class SharedClass: NSObject {//This is shared class
static let sharedInstance = SharedClass()
//Show alert
func alert(view: UIViewController, title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(defaultAction)
DispatchQueue.main.async(execute: {
view.present(alert, animated: true)
})
}
private override init() {
}
}
Now call alert like this in every ware
SharedClass.SharedInstance.alert(view: self, title: "Your title here", message: "Your message here")
Method 3 :
PRESENT ALERT TOP OF ALL WINDOWS
If you want to present alert on top of all views, use this code
func alertWindow(title: String, message: String) {
DispatchQueue.main.async(execute: {
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1
let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert2.addAction(defaultAction2)
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
})
}
Function calling
SharedClass.sharedInstance.alertWindow(title:"This your title", message:"This is your message")
Method 4 :
Alert with Extension
extension UIViewController {
func showAlert(withTitle title: String, withMessage message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(ok)
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
}
}
Now call like this
//Call showAlert function in your class
@IBAction func onClickAlert(_ sender: UIButton) {
showAlert(withTitle:"Your Title Here", withMessage: "YourCustomMessageHere")
}
Method 5 :
ALERT WITH TEXTFIELDS
If you want to add textfields to alert.
//Global variables
var name:String?
var login:String?
//Call this function like this: alertWithTF()
//Add textfields to alert
func alertWithTF() {
let alert = UIAlertController(title: "Login", message: "Enter username&password", preferredStyle: .alert)
// Login button
let loginAction = UIAlertAction(title: "Login", style: .default, handler: { (action) -> Void in
// Get TextFields text
let usernameTxt = alert.textFields![0]
let passwordTxt = alert.textFields![1]
//Asign textfileds text to our global varibles
self.name = usernameTxt.text
self.login = passwordTxt.text
print("USERNAME: (self.name!)nPASSWORD: (self.login!)")
})
// Cancel button
let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in })
//1 textField for username
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter username"
//If required mention keyboard type, delegates, text sixe and font etc...
//EX:
textField.keyboardType = .default
}
//2nd textField for password
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter password"
textField.isSecureTextEntry = true
}
// Add actions
alert.addAction(loginAction)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
add a comment |
In Swift 4.2 and Xcode 10
Method 1 :
SIMPLE ALERT
let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(ok)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
Method 2 :
ALERT WITH SHARED CLASS
If you want Shared class style(Write once use every where)
import UIKit
class SharedClass: NSObject {//This is shared class
static let sharedInstance = SharedClass()
//Show alert
func alert(view: UIViewController, title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(defaultAction)
DispatchQueue.main.async(execute: {
view.present(alert, animated: true)
})
}
private override init() {
}
}
Now call alert like this in every ware
SharedClass.SharedInstance.alert(view: self, title: "Your title here", message: "Your message here")
Method 3 :
PRESENT ALERT TOP OF ALL WINDOWS
If you want to present alert on top of all views, use this code
func alertWindow(title: String, message: String) {
DispatchQueue.main.async(execute: {
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1
let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert2.addAction(defaultAction2)
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
})
}
Function calling
SharedClass.sharedInstance.alertWindow(title:"This your title", message:"This is your message")
Method 4 :
Alert with Extension
extension UIViewController {
func showAlert(withTitle title: String, withMessage message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(ok)
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
}
}
Now call like this
//Call showAlert function in your class
@IBAction func onClickAlert(_ sender: UIButton) {
showAlert(withTitle:"Your Title Here", withMessage: "YourCustomMessageHere")
}
Method 5 :
ALERT WITH TEXTFIELDS
If you want to add textfields to alert.
//Global variables
var name:String?
var login:String?
//Call this function like this: alertWithTF()
//Add textfields to alert
func alertWithTF() {
let alert = UIAlertController(title: "Login", message: "Enter username&password", preferredStyle: .alert)
// Login button
let loginAction = UIAlertAction(title: "Login", style: .default, handler: { (action) -> Void in
// Get TextFields text
let usernameTxt = alert.textFields![0]
let passwordTxt = alert.textFields![1]
//Asign textfileds text to our global varibles
self.name = usernameTxt.text
self.login = passwordTxt.text
print("USERNAME: (self.name!)nPASSWORD: (self.login!)")
})
// Cancel button
let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in })
//1 textField for username
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter username"
//If required mention keyboard type, delegates, text sixe and font etc...
//EX:
textField.keyboardType = .default
}
//2nd textField for password
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter password"
textField.isSecureTextEntry = true
}
// Add actions
alert.addAction(loginAction)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
In Swift 4.2 and Xcode 10
Method 1 :
SIMPLE ALERT
let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(ok)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
Method 2 :
ALERT WITH SHARED CLASS
If you want Shared class style(Write once use every where)
import UIKit
class SharedClass: NSObject {//This is shared class
static let sharedInstance = SharedClass()
//Show alert
func alert(view: UIViewController, title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(defaultAction)
DispatchQueue.main.async(execute: {
view.present(alert, animated: true)
})
}
private override init() {
}
}
Now call alert like this in every ware
SharedClass.SharedInstance.alert(view: self, title: "Your title here", message: "Your message here")
Method 3 :
PRESENT ALERT TOP OF ALL WINDOWS
If you want to present alert on top of all views, use this code
func alertWindow(title: String, message: String) {
DispatchQueue.main.async(execute: {
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1
let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert2.addAction(defaultAction2)
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
})
}
Function calling
SharedClass.sharedInstance.alertWindow(title:"This your title", message:"This is your message")
Method 4 :
Alert with Extension
extension UIViewController {
func showAlert(withTitle title: String, withMessage message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(ok)
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
}
}
Now call like this
//Call showAlert function in your class
@IBAction func onClickAlert(_ sender: UIButton) {
showAlert(withTitle:"Your Title Here", withMessage: "YourCustomMessageHere")
}
Method 5 :
ALERT WITH TEXTFIELDS
If you want to add textfields to alert.
//Global variables
var name:String?
var login:String?
//Call this function like this: alertWithTF()
//Add textfields to alert
func alertWithTF() {
let alert = UIAlertController(title: "Login", message: "Enter username&password", preferredStyle: .alert)
// Login button
let loginAction = UIAlertAction(title: "Login", style: .default, handler: { (action) -> Void in
// Get TextFields text
let usernameTxt = alert.textFields![0]
let passwordTxt = alert.textFields![1]
//Asign textfileds text to our global varibles
self.name = usernameTxt.text
self.login = passwordTxt.text
print("USERNAME: (self.name!)nPASSWORD: (self.login!)")
})
// Cancel button
let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in })
//1 textField for username
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter username"
//If required mention keyboard type, delegates, text sixe and font etc...
//EX:
textField.keyboardType = .default
}
//2nd textField for password
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter password"
textField.isSecureTextEntry = true
}
// Add actions
alert.addAction(loginAction)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
edited Jan 5 at 11:23
answered Aug 16 '18 at 12:17
iOSiOS
2,86722048
2,86722048
add a comment |
add a comment |
If you're targeting iOS 7 and 8, you need something like this to make sure you're using the right method for each version, because UIAlertView
is deprecated in iOS 8, but UIAlertController
is not available in iOS 7:
func alert(title: String, message: String) {
if let getModernAlert: AnyClass = NSClassFromString("UIAlertController") { // iOS 8
let myAlert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
myAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(myAlert, animated: true, completion: nil)
} else { // iOS 7
let alert: UIAlertView = UIAlertView()
alert.delegate = self
alert.title = title
alert.message = message
alert.addButtonWithTitle("OK")
alert.show()
}
}
Or you can save time and just useUIAlertView
until you drop support for iOS 7. Apple won't reject your app for that.
– cprcrack
Jan 19 '15 at 16:17
2
Deprecation doesn't mean "don't use this" or that it would be the "wrong method", it just means it will not work later on. There's no need to specifically use UIAlertController on iOS8 if one just needs basic alerts. They will work as before. There are many APIs that have been deprecated in iOS4 or 5 and still work in iOS8. But of course apps targeting a higher iOS level should not use them and that's why there is a deprecation warning.
– Sami Kuhmonen
Apr 2 '15 at 7:47
1
@SamiKuhmonen No, but it makes it clearer why you're doing what you're doing and makes it easier to remove support for deprecated methods when your minimum version is high enough to do so.
– AstroCB
Apr 2 '15 at 10:17
add a comment |
If you're targeting iOS 7 and 8, you need something like this to make sure you're using the right method for each version, because UIAlertView
is deprecated in iOS 8, but UIAlertController
is not available in iOS 7:
func alert(title: String, message: String) {
if let getModernAlert: AnyClass = NSClassFromString("UIAlertController") { // iOS 8
let myAlert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
myAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(myAlert, animated: true, completion: nil)
} else { // iOS 7
let alert: UIAlertView = UIAlertView()
alert.delegate = self
alert.title = title
alert.message = message
alert.addButtonWithTitle("OK")
alert.show()
}
}
Or you can save time and just useUIAlertView
until you drop support for iOS 7. Apple won't reject your app for that.
– cprcrack
Jan 19 '15 at 16:17
2
Deprecation doesn't mean "don't use this" or that it would be the "wrong method", it just means it will not work later on. There's no need to specifically use UIAlertController on iOS8 if one just needs basic alerts. They will work as before. There are many APIs that have been deprecated in iOS4 or 5 and still work in iOS8. But of course apps targeting a higher iOS level should not use them and that's why there is a deprecation warning.
– Sami Kuhmonen
Apr 2 '15 at 7:47
1
@SamiKuhmonen No, but it makes it clearer why you're doing what you're doing and makes it easier to remove support for deprecated methods when your minimum version is high enough to do so.
– AstroCB
Apr 2 '15 at 10:17
add a comment |
If you're targeting iOS 7 and 8, you need something like this to make sure you're using the right method for each version, because UIAlertView
is deprecated in iOS 8, but UIAlertController
is not available in iOS 7:
func alert(title: String, message: String) {
if let getModernAlert: AnyClass = NSClassFromString("UIAlertController") { // iOS 8
let myAlert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
myAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(myAlert, animated: true, completion: nil)
} else { // iOS 7
let alert: UIAlertView = UIAlertView()
alert.delegate = self
alert.title = title
alert.message = message
alert.addButtonWithTitle("OK")
alert.show()
}
}
If you're targeting iOS 7 and 8, you need something like this to make sure you're using the right method for each version, because UIAlertView
is deprecated in iOS 8, but UIAlertController
is not available in iOS 7:
func alert(title: String, message: String) {
if let getModernAlert: AnyClass = NSClassFromString("UIAlertController") { // iOS 8
let myAlert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
myAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(myAlert, animated: true, completion: nil)
} else { // iOS 7
let alert: UIAlertView = UIAlertView()
alert.delegate = self
alert.title = title
alert.message = message
alert.addButtonWithTitle("OK")
alert.show()
}
}
answered Jan 13 '15 at 21:14
AstroCBAstroCB
10.4k144966
10.4k144966
Or you can save time and just useUIAlertView
until you drop support for iOS 7. Apple won't reject your app for that.
– cprcrack
Jan 19 '15 at 16:17
2
Deprecation doesn't mean "don't use this" or that it would be the "wrong method", it just means it will not work later on. There's no need to specifically use UIAlertController on iOS8 if one just needs basic alerts. They will work as before. There are many APIs that have been deprecated in iOS4 or 5 and still work in iOS8. But of course apps targeting a higher iOS level should not use them and that's why there is a deprecation warning.
– Sami Kuhmonen
Apr 2 '15 at 7:47
1
@SamiKuhmonen No, but it makes it clearer why you're doing what you're doing and makes it easier to remove support for deprecated methods when your minimum version is high enough to do so.
– AstroCB
Apr 2 '15 at 10:17
add a comment |
Or you can save time and just useUIAlertView
until you drop support for iOS 7. Apple won't reject your app for that.
– cprcrack
Jan 19 '15 at 16:17
2
Deprecation doesn't mean "don't use this" or that it would be the "wrong method", it just means it will not work later on. There's no need to specifically use UIAlertController on iOS8 if one just needs basic alerts. They will work as before. There are many APIs that have been deprecated in iOS4 or 5 and still work in iOS8. But of course apps targeting a higher iOS level should not use them and that's why there is a deprecation warning.
– Sami Kuhmonen
Apr 2 '15 at 7:47
1
@SamiKuhmonen No, but it makes it clearer why you're doing what you're doing and makes it easier to remove support for deprecated methods when your minimum version is high enough to do so.
– AstroCB
Apr 2 '15 at 10:17
Or you can save time and just use
UIAlertView
until you drop support for iOS 7. Apple won't reject your app for that.– cprcrack
Jan 19 '15 at 16:17
Or you can save time and just use
UIAlertView
until you drop support for iOS 7. Apple won't reject your app for that.– cprcrack
Jan 19 '15 at 16:17
2
2
Deprecation doesn't mean "don't use this" or that it would be the "wrong method", it just means it will not work later on. There's no need to specifically use UIAlertController on iOS8 if one just needs basic alerts. They will work as before. There are many APIs that have been deprecated in iOS4 or 5 and still work in iOS8. But of course apps targeting a higher iOS level should not use them and that's why there is a deprecation warning.
– Sami Kuhmonen
Apr 2 '15 at 7:47
Deprecation doesn't mean "don't use this" or that it would be the "wrong method", it just means it will not work later on. There's no need to specifically use UIAlertController on iOS8 if one just needs basic alerts. They will work as before. There are many APIs that have been deprecated in iOS4 or 5 and still work in iOS8. But of course apps targeting a higher iOS level should not use them and that's why there is a deprecation warning.
– Sami Kuhmonen
Apr 2 '15 at 7:47
1
1
@SamiKuhmonen No, but it makes it clearer why you're doing what you're doing and makes it easier to remove support for deprecated methods when your minimum version is high enough to do so.
– AstroCB
Apr 2 '15 at 10:17
@SamiKuhmonen No, but it makes it clearer why you're doing what you're doing and makes it easier to remove support for deprecated methods when your minimum version is high enough to do so.
– AstroCB
Apr 2 '15 at 10:17
add a comment |
Show UIAlertView in swift language :-
Protocol UIAlertViewDelegate
let alert = UIAlertView(title: "alertView", message: "This is alertView", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles: "Done", "Delete")
alert.show()
Show UIAlertViewController in swift language :-
let alert = UIAlertController(title: "Error", message: "Enter data in Text fields", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
This answers the question directly and is correct
– Fraser
Aug 19 '15 at 1:29
add a comment |
Show UIAlertView in swift language :-
Protocol UIAlertViewDelegate
let alert = UIAlertView(title: "alertView", message: "This is alertView", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles: "Done", "Delete")
alert.show()
Show UIAlertViewController in swift language :-
let alert = UIAlertController(title: "Error", message: "Enter data in Text fields", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
This answers the question directly and is correct
– Fraser
Aug 19 '15 at 1:29
add a comment |
Show UIAlertView in swift language :-
Protocol UIAlertViewDelegate
let alert = UIAlertView(title: "alertView", message: "This is alertView", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles: "Done", "Delete")
alert.show()
Show UIAlertViewController in swift language :-
let alert = UIAlertController(title: "Error", message: "Enter data in Text fields", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Show UIAlertView in swift language :-
Protocol UIAlertViewDelegate
let alert = UIAlertView(title: "alertView", message: "This is alertView", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles: "Done", "Delete")
alert.show()
Show UIAlertViewController in swift language :-
let alert = UIAlertController(title: "Error", message: "Enter data in Text fields", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
edited Oct 8 '14 at 13:41
HpTerm
6,595124667
6,595124667
answered Sep 3 '14 at 12:53
Anit KumarAnit Kumar
4,77011421
4,77011421
This answers the question directly and is correct
– Fraser
Aug 19 '15 at 1:29
add a comment |
This answers the question directly and is correct
– Fraser
Aug 19 '15 at 1:29
This answers the question directly and is correct
– Fraser
Aug 19 '15 at 1:29
This answers the question directly and is correct
– Fraser
Aug 19 '15 at 1:29
add a comment |
Simply do not provide otherButtonTitles in the constructor.
let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
But I do agree with Oscar, this class is deprecated in iOS 8, so there won't be no use of UIAlertView if you're doing an iOS 8 only app. Otherwise the code above will work.
add a comment |
Simply do not provide otherButtonTitles in the constructor.
let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
But I do agree with Oscar, this class is deprecated in iOS 8, so there won't be no use of UIAlertView if you're doing an iOS 8 only app. Otherwise the code above will work.
add a comment |
Simply do not provide otherButtonTitles in the constructor.
let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
But I do agree with Oscar, this class is deprecated in iOS 8, so there won't be no use of UIAlertView if you're doing an iOS 8 only app. Otherwise the code above will work.
Simply do not provide otherButtonTitles in the constructor.
let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
But I do agree with Oscar, this class is deprecated in iOS 8, so there won't be no use of UIAlertView if you're doing an iOS 8 only app. Otherwise the code above will work.
answered Dec 22 '14 at 14:51
PeymankhPeymankh
1,3771827
1,3771827
add a comment |
add a comment |
With the protocol extensions of Swift 2, you can make a protocol that provides a default implementation to your view controllers:
ShowsAlert.swift
import UIKit
protocol ShowsAlert {}
extension ShowsAlert where Self: UIViewController {
func showAlert(title: String = "Error", message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
}
}
ViewController.swift
class ViewController: UIViewController, ShowsAlert {
override func viewDidLoad() {
super.viewDidLoad()
showAlert(message: "Hey there, I am an error message!")
}
}
1
Works perfectly. For Swift3 change 'presentViewController' to 'present'.
– Vincent
Jan 18 '17 at 8:38
add a comment |
With the protocol extensions of Swift 2, you can make a protocol that provides a default implementation to your view controllers:
ShowsAlert.swift
import UIKit
protocol ShowsAlert {}
extension ShowsAlert where Self: UIViewController {
func showAlert(title: String = "Error", message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
}
}
ViewController.swift
class ViewController: UIViewController, ShowsAlert {
override func viewDidLoad() {
super.viewDidLoad()
showAlert(message: "Hey there, I am an error message!")
}
}
1
Works perfectly. For Swift3 change 'presentViewController' to 'present'.
– Vincent
Jan 18 '17 at 8:38
add a comment |
With the protocol extensions of Swift 2, you can make a protocol that provides a default implementation to your view controllers:
ShowsAlert.swift
import UIKit
protocol ShowsAlert {}
extension ShowsAlert where Self: UIViewController {
func showAlert(title: String = "Error", message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
}
}
ViewController.swift
class ViewController: UIViewController, ShowsAlert {
override func viewDidLoad() {
super.viewDidLoad()
showAlert(message: "Hey there, I am an error message!")
}
}
With the protocol extensions of Swift 2, you can make a protocol that provides a default implementation to your view controllers:
ShowsAlert.swift
import UIKit
protocol ShowsAlert {}
extension ShowsAlert where Self: UIViewController {
func showAlert(title: String = "Error", message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
}
}
ViewController.swift
class ViewController: UIViewController, ShowsAlert {
override func viewDidLoad() {
super.viewDidLoad()
showAlert(message: "Hey there, I am an error message!")
}
}
edited Jan 4 '16 at 13:32
answered Oct 7 '15 at 13:33
knshnknshn
2,51611420
2,51611420
1
Works perfectly. For Swift3 change 'presentViewController' to 'present'.
– Vincent
Jan 18 '17 at 8:38
add a comment |
1
Works perfectly. For Swift3 change 'presentViewController' to 'present'.
– Vincent
Jan 18 '17 at 8:38
1
1
Works perfectly. For Swift3 change 'presentViewController' to 'present'.
– Vincent
Jan 18 '17 at 8:38
Works perfectly. For Swift3 change 'presentViewController' to 'present'.
– Vincent
Jan 18 '17 at 8:38
add a comment |
I found this one,
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
not good though, but it works :)
Update:
but I have found on header file as:
extension UIAlertView {
convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}
somebody may can explain this.
Apparently UIAlertView has been deprecated in iOS 8 and we now use UIAlertController with a preferred style of UIAlertControllerStyleAlert.
– BlueBear
Jun 3 '14 at 19:06
6
If you run an app that needs to be backwards compatible to iOS7.1 and you're writing it in Swift, the UIAlertController will crash the target device. You need to support the legacy UIAlertViews for iOS7.
– Joe
Jun 22 '14 at 4:02
I think that it's not Swift that would cause a crash, but rather the fact that the UIAlertController is not available before iOS 8
– Frédéric Adda
Aug 24 '14 at 20:12
add a comment |
I found this one,
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
not good though, but it works :)
Update:
but I have found on header file as:
extension UIAlertView {
convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}
somebody may can explain this.
Apparently UIAlertView has been deprecated in iOS 8 and we now use UIAlertController with a preferred style of UIAlertControllerStyleAlert.
– BlueBear
Jun 3 '14 at 19:06
6
If you run an app that needs to be backwards compatible to iOS7.1 and you're writing it in Swift, the UIAlertController will crash the target device. You need to support the legacy UIAlertViews for iOS7.
– Joe
Jun 22 '14 at 4:02
I think that it's not Swift that would cause a crash, but rather the fact that the UIAlertController is not available before iOS 8
– Frédéric Adda
Aug 24 '14 at 20:12
add a comment |
I found this one,
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
not good though, but it works :)
Update:
but I have found on header file as:
extension UIAlertView {
convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}
somebody may can explain this.
I found this one,
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
not good though, but it works :)
Update:
but I have found on header file as:
extension UIAlertView {
convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}
somebody may can explain this.
answered Jun 3 '14 at 19:05
Mujah MaskeyMujah Maskey
6,46163159
6,46163159
Apparently UIAlertView has been deprecated in iOS 8 and we now use UIAlertController with a preferred style of UIAlertControllerStyleAlert.
– BlueBear
Jun 3 '14 at 19:06
6
If you run an app that needs to be backwards compatible to iOS7.1 and you're writing it in Swift, the UIAlertController will crash the target device. You need to support the legacy UIAlertViews for iOS7.
– Joe
Jun 22 '14 at 4:02
I think that it's not Swift that would cause a crash, but rather the fact that the UIAlertController is not available before iOS 8
– Frédéric Adda
Aug 24 '14 at 20:12
add a comment |
Apparently UIAlertView has been deprecated in iOS 8 and we now use UIAlertController with a preferred style of UIAlertControllerStyleAlert.
– BlueBear
Jun 3 '14 at 19:06
6
If you run an app that needs to be backwards compatible to iOS7.1 and you're writing it in Swift, the UIAlertController will crash the target device. You need to support the legacy UIAlertViews for iOS7.
– Joe
Jun 22 '14 at 4:02
I think that it's not Swift that would cause a crash, but rather the fact that the UIAlertController is not available before iOS 8
– Frédéric Adda
Aug 24 '14 at 20:12
Apparently UIAlertView has been deprecated in iOS 8 and we now use UIAlertController with a preferred style of UIAlertControllerStyleAlert.
– BlueBear
Jun 3 '14 at 19:06
Apparently UIAlertView has been deprecated in iOS 8 and we now use UIAlertController with a preferred style of UIAlertControllerStyleAlert.
– BlueBear
Jun 3 '14 at 19:06
6
6
If you run an app that needs to be backwards compatible to iOS7.1 and you're writing it in Swift, the UIAlertController will crash the target device. You need to support the legacy UIAlertViews for iOS7.
– Joe
Jun 22 '14 at 4:02
If you run an app that needs to be backwards compatible to iOS7.1 and you're writing it in Swift, the UIAlertController will crash the target device. You need to support the legacy UIAlertViews for iOS7.
– Joe
Jun 22 '14 at 4:02
I think that it's not Swift that would cause a crash, but rather the fact that the UIAlertController is not available before iOS 8
– Frédéric Adda
Aug 24 '14 at 20:12
I think that it's not Swift that would cause a crash, but rather the fact that the UIAlertController is not available before iOS 8
– Frédéric Adda
Aug 24 '14 at 20:12
add a comment |
For SWIFT4, I think, extending UIViewController
and creating a reusable confirmation control is the most elegant way.
You can extend the UIViewController
as below:
extension UIViewController {
func AskConfirmation (title:String, message:String, completion:@escaping (_ result:Bool) -> Void) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
completion(true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
completion(false)
}))
}
}
Then you can use it anytime:
AskConfirmation(title: "YOUR MESSAGE TITLE", message: "YOUR MESSAGE") { (result) in
if result { //User has clicked on Ok
} else { //User has clicked on Cancel
}
}
add a comment |
For SWIFT4, I think, extending UIViewController
and creating a reusable confirmation control is the most elegant way.
You can extend the UIViewController
as below:
extension UIViewController {
func AskConfirmation (title:String, message:String, completion:@escaping (_ result:Bool) -> Void) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
completion(true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
completion(false)
}))
}
}
Then you can use it anytime:
AskConfirmation(title: "YOUR MESSAGE TITLE", message: "YOUR MESSAGE") { (result) in
if result { //User has clicked on Ok
} else { //User has clicked on Cancel
}
}
add a comment |
For SWIFT4, I think, extending UIViewController
and creating a reusable confirmation control is the most elegant way.
You can extend the UIViewController
as below:
extension UIViewController {
func AskConfirmation (title:String, message:String, completion:@escaping (_ result:Bool) -> Void) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
completion(true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
completion(false)
}))
}
}
Then you can use it anytime:
AskConfirmation(title: "YOUR MESSAGE TITLE", message: "YOUR MESSAGE") { (result) in
if result { //User has clicked on Ok
} else { //User has clicked on Cancel
}
}
For SWIFT4, I think, extending UIViewController
and creating a reusable confirmation control is the most elegant way.
You can extend the UIViewController
as below:
extension UIViewController {
func AskConfirmation (title:String, message:String, completion:@escaping (_ result:Bool) -> Void) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
completion(true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
completion(false)
}))
}
}
Then you can use it anytime:
AskConfirmation(title: "YOUR MESSAGE TITLE", message: "YOUR MESSAGE") { (result) in
if result { //User has clicked on Ok
} else { //User has clicked on Cancel
}
}
edited Mar 4 '18 at 1:23
Rishil P.
1,3661722
1,3661722
answered Jan 20 '18 at 15:04
emreoktememreoktem
1,8781223
1,8781223
add a comment |
add a comment |
class Preview: UIViewController , UIAlertViewDelegate
{
@IBAction func MoreBtnClicked(sender: AnyObject)
{
var moreAlert=UIAlertView(title: "Photo", message: "", delegate: self, cancelButtonTitle: "No Thanks!", otherButtonTitles: "Save Image", "Email", "Facebook", "Whatsapp" )
moreAlert.show()
moreAlert.tag=111;
}
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int)
{
if alertView.tag==111
{
if buttonIndex==0
{
println("No Thanks!")
}
else if buttonIndex==1
{
println("Save Image")
}
else if buttonIndex == 2
{
println("Email")
}
else if buttonIndex == 3
{
println("Facebook")
}
else if buttonIndex == 4
{
println("Whatsapp")
}
}
}
}
Just writing a lump of code is not very useful. When answering any question (specially an old question with several answers including an accepted answer) please write more than a piece of code. Please add an explanation of what your code does, how it answers the question and how it is different (or better) than the other answers.
– AdrianHHH
Jul 10 '15 at 13:00
Fantastic answer, Jayesh, thanks for that.
– Fattie
Dec 15 '16 at 23:37
add a comment |
class Preview: UIViewController , UIAlertViewDelegate
{
@IBAction func MoreBtnClicked(sender: AnyObject)
{
var moreAlert=UIAlertView(title: "Photo", message: "", delegate: self, cancelButtonTitle: "No Thanks!", otherButtonTitles: "Save Image", "Email", "Facebook", "Whatsapp" )
moreAlert.show()
moreAlert.tag=111;
}
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int)
{
if alertView.tag==111
{
if buttonIndex==0
{
println("No Thanks!")
}
else if buttonIndex==1
{
println("Save Image")
}
else if buttonIndex == 2
{
println("Email")
}
else if buttonIndex == 3
{
println("Facebook")
}
else if buttonIndex == 4
{
println("Whatsapp")
}
}
}
}
Just writing a lump of code is not very useful. When answering any question (specially an old question with several answers including an accepted answer) please write more than a piece of code. Please add an explanation of what your code does, how it answers the question and how it is different (or better) than the other answers.
– AdrianHHH
Jul 10 '15 at 13:00
Fantastic answer, Jayesh, thanks for that.
– Fattie
Dec 15 '16 at 23:37
add a comment |
class Preview: UIViewController , UIAlertViewDelegate
{
@IBAction func MoreBtnClicked(sender: AnyObject)
{
var moreAlert=UIAlertView(title: "Photo", message: "", delegate: self, cancelButtonTitle: "No Thanks!", otherButtonTitles: "Save Image", "Email", "Facebook", "Whatsapp" )
moreAlert.show()
moreAlert.tag=111;
}
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int)
{
if alertView.tag==111
{
if buttonIndex==0
{
println("No Thanks!")
}
else if buttonIndex==1
{
println("Save Image")
}
else if buttonIndex == 2
{
println("Email")
}
else if buttonIndex == 3
{
println("Facebook")
}
else if buttonIndex == 4
{
println("Whatsapp")
}
}
}
}
class Preview: UIViewController , UIAlertViewDelegate
{
@IBAction func MoreBtnClicked(sender: AnyObject)
{
var moreAlert=UIAlertView(title: "Photo", message: "", delegate: self, cancelButtonTitle: "No Thanks!", otherButtonTitles: "Save Image", "Email", "Facebook", "Whatsapp" )
moreAlert.show()
moreAlert.tag=111;
}
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int)
{
if alertView.tag==111
{
if buttonIndex==0
{
println("No Thanks!")
}
else if buttonIndex==1
{
println("Save Image")
}
else if buttonIndex == 2
{
println("Email")
}
else if buttonIndex == 3
{
println("Facebook")
}
else if buttonIndex == 4
{
println("Whatsapp")
}
}
}
}
answered Jul 10 '15 at 12:35
Jayesh MiruliyaJayesh Miruliya
2,3131317
2,3131317
Just writing a lump of code is not very useful. When answering any question (specially an old question with several answers including an accepted answer) please write more than a piece of code. Please add an explanation of what your code does, how it answers the question and how it is different (or better) than the other answers.
– AdrianHHH
Jul 10 '15 at 13:00
Fantastic answer, Jayesh, thanks for that.
– Fattie
Dec 15 '16 at 23:37
add a comment |
Just writing a lump of code is not very useful. When answering any question (specially an old question with several answers including an accepted answer) please write more than a piece of code. Please add an explanation of what your code does, how it answers the question and how it is different (or better) than the other answers.
– AdrianHHH
Jul 10 '15 at 13:00
Fantastic answer, Jayesh, thanks for that.
– Fattie
Dec 15 '16 at 23:37
Just writing a lump of code is not very useful. When answering any question (specially an old question with several answers including an accepted answer) please write more than a piece of code. Please add an explanation of what your code does, how it answers the question and how it is different (or better) than the other answers.
– AdrianHHH
Jul 10 '15 at 13:00
Just writing a lump of code is not very useful. When answering any question (specially an old question with several answers including an accepted answer) please write more than a piece of code. Please add an explanation of what your code does, how it answers the question and how it is different (or better) than the other answers.
– AdrianHHH
Jul 10 '15 at 13:00
Fantastic answer, Jayesh, thanks for that.
– Fattie
Dec 15 '16 at 23:37
Fantastic answer, Jayesh, thanks for that.
– Fattie
Dec 15 '16 at 23:37
add a comment |
I have another trick. Suppose you have 5 classes where a logout alert to be applied. Try with swift class extension.
File- New- Swift class- Name it.
Add the following:
public extension UIViewController
{
func makeLogOutAlert()
{
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
self.navigationController?.popToRootViewControllerAnimated(true)
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
refreshAlert .dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(refreshAlert, animated: true, completion: nil)
}
}
Implement using : self.makeLogOutAlert(). Hope it helps.
add a comment |
I have another trick. Suppose you have 5 classes where a logout alert to be applied. Try with swift class extension.
File- New- Swift class- Name it.
Add the following:
public extension UIViewController
{
func makeLogOutAlert()
{
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
self.navigationController?.popToRootViewControllerAnimated(true)
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
refreshAlert .dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(refreshAlert, animated: true, completion: nil)
}
}
Implement using : self.makeLogOutAlert(). Hope it helps.
add a comment |
I have another trick. Suppose you have 5 classes where a logout alert to be applied. Try with swift class extension.
File- New- Swift class- Name it.
Add the following:
public extension UIViewController
{
func makeLogOutAlert()
{
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
self.navigationController?.popToRootViewControllerAnimated(true)
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
refreshAlert .dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(refreshAlert, animated: true, completion: nil)
}
}
Implement using : self.makeLogOutAlert(). Hope it helps.
I have another trick. Suppose you have 5 classes where a logout alert to be applied. Try with swift class extension.
File- New- Swift class- Name it.
Add the following:
public extension UIViewController
{
func makeLogOutAlert()
{
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
self.navigationController?.popToRootViewControllerAnimated(true)
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
refreshAlert .dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(refreshAlert, animated: true, completion: nil)
}
}
Implement using : self.makeLogOutAlert(). Hope it helps.
edited Oct 8 '15 at 14:50
Luke Berry
1,14721430
1,14721430
answered Sep 17 '15 at 13:48
A.GA.G
10.6k7152
10.6k7152
add a comment |
add a comment |
I have made a singleton class to make this convenient to use from anywhere in your app: https://github.com/Swinny1989/Swift-Popups
You can then create a popup with multiple buttons like this:
Popups.SharedInstance.ShowAlert(self, title: "Title goes here", message: "Messages goes here", buttons: ["button one" , "button two"]) { (buttonPressed) -> Void in
if buttonPressed == "button one" {
//Code here
} else if buttonPressed == "button two" {
// Code here
}
}
or popups with a single button like this:
Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")
Thanks. I submit some issue there
– djdance
Jan 7 '16 at 19:32
1
Hey @Swinny89 Thanks so much man for sharing this solution with us! I got stuck with the closure thing and you just saved me!
– Bruno Campos
Mar 29 '18 at 17:15
add a comment |
I have made a singleton class to make this convenient to use from anywhere in your app: https://github.com/Swinny1989/Swift-Popups
You can then create a popup with multiple buttons like this:
Popups.SharedInstance.ShowAlert(self, title: "Title goes here", message: "Messages goes here", buttons: ["button one" , "button two"]) { (buttonPressed) -> Void in
if buttonPressed == "button one" {
//Code here
} else if buttonPressed == "button two" {
// Code here
}
}
or popups with a single button like this:
Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")
Thanks. I submit some issue there
– djdance
Jan 7 '16 at 19:32
1
Hey @Swinny89 Thanks so much man for sharing this solution with us! I got stuck with the closure thing and you just saved me!
– Bruno Campos
Mar 29 '18 at 17:15
add a comment |
I have made a singleton class to make this convenient to use from anywhere in your app: https://github.com/Swinny1989/Swift-Popups
You can then create a popup with multiple buttons like this:
Popups.SharedInstance.ShowAlert(self, title: "Title goes here", message: "Messages goes here", buttons: ["button one" , "button two"]) { (buttonPressed) -> Void in
if buttonPressed == "button one" {
//Code here
} else if buttonPressed == "button two" {
// Code here
}
}
or popups with a single button like this:
Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")
I have made a singleton class to make this convenient to use from anywhere in your app: https://github.com/Swinny1989/Swift-Popups
You can then create a popup with multiple buttons like this:
Popups.SharedInstance.ShowAlert(self, title: "Title goes here", message: "Messages goes here", buttons: ["button one" , "button two"]) { (buttonPressed) -> Void in
if buttonPressed == "button one" {
//Code here
} else if buttonPressed == "button two" {
// Code here
}
}
or popups with a single button like this:
Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")
answered Oct 26 '15 at 9:31
Swinny89Swinny89
5,58222349
5,58222349
Thanks. I submit some issue there
– djdance
Jan 7 '16 at 19:32
1
Hey @Swinny89 Thanks so much man for sharing this solution with us! I got stuck with the closure thing and you just saved me!
– Bruno Campos
Mar 29 '18 at 17:15
add a comment |
Thanks. I submit some issue there
– djdance
Jan 7 '16 at 19:32
1
Hey @Swinny89 Thanks so much man for sharing this solution with us! I got stuck with the closure thing and you just saved me!
– Bruno Campos
Mar 29 '18 at 17:15
Thanks. I submit some issue there
– djdance
Jan 7 '16 at 19:32
Thanks. I submit some issue there
– djdance
Jan 7 '16 at 19:32
1
1
Hey @Swinny89 Thanks so much man for sharing this solution with us! I got stuck with the closure thing and you just saved me!
– Bruno Campos
Mar 29 '18 at 17:15
Hey @Swinny89 Thanks so much man for sharing this solution with us! I got stuck with the closure thing and you just saved me!
– Bruno Campos
Mar 29 '18 at 17:15
add a comment |
Swift 3
The following is a simple example of how to create a simple alert with one button with Swift 3.
let alert = UIAlertController(title: "Title",
message: "Message",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)
In the above example the handle callback of the action has been omitted because the default behaviour of an alert view with one button is to disappear when the button is clicked.
Here is how to create another action, which could be added to the alert with "alert.addAction(action)". The different styles are .default, .destructive and .cancel.
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
}
add a comment |
Swift 3
The following is a simple example of how to create a simple alert with one button with Swift 3.
let alert = UIAlertController(title: "Title",
message: "Message",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)
In the above example the handle callback of the action has been omitted because the default behaviour of an alert view with one button is to disappear when the button is clicked.
Here is how to create another action, which could be added to the alert with "alert.addAction(action)". The different styles are .default, .destructive and .cancel.
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
}
add a comment |
Swift 3
The following is a simple example of how to create a simple alert with one button with Swift 3.
let alert = UIAlertController(title: "Title",
message: "Message",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)
In the above example the handle callback of the action has been omitted because the default behaviour of an alert view with one button is to disappear when the button is clicked.
Here is how to create another action, which could be added to the alert with "alert.addAction(action)". The different styles are .default, .destructive and .cancel.
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
}
Swift 3
The following is a simple example of how to create a simple alert with one button with Swift 3.
let alert = UIAlertController(title: "Title",
message: "Message",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)
In the above example the handle callback of the action has been omitted because the default behaviour of an alert view with one button is to disappear when the button is clicked.
Here is how to create another action, which could be added to the alert with "alert.addAction(action)". The different styles are .default, .destructive and .cancel.
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
}
edited Oct 5 '16 at 7:25
answered Sep 28 '16 at 12:52
user2359168
add a comment |
add a comment |
I got the following UIAlertView
initialization code to compile without errors (I thing the last, varyadic part is tricky perhaps). But I had to make sure the class of self
(which I am passing as the delegate) was adopting the UIAlertViewDelegate
protocol for the compile errors to go away:
let alertView = UIAlertView(
title: "My Title",
message: "My Message",
delegate: self,
cancelButtonTitle: "Cancel",
otherButtonTitles: "OK"
)
By the way, this is the error I was getting (as of Xcode 6.4):
Cannot find an initializer for type 'UIAlertView' that accepts an
argument list of type '(title: String, message: String, delegate:
MyViewController, cancelButtonTitle: String, otherButtonTitles:
String)'
As others mentioned, you should migrate to UIAlertController if you can target iOS 8.x+. To support iOS 7, use the code above (iOS 6 is not supported by Swift).
add a comment |
I got the following UIAlertView
initialization code to compile without errors (I thing the last, varyadic part is tricky perhaps). But I had to make sure the class of self
(which I am passing as the delegate) was adopting the UIAlertViewDelegate
protocol for the compile errors to go away:
let alertView = UIAlertView(
title: "My Title",
message: "My Message",
delegate: self,
cancelButtonTitle: "Cancel",
otherButtonTitles: "OK"
)
By the way, this is the error I was getting (as of Xcode 6.4):
Cannot find an initializer for type 'UIAlertView' that accepts an
argument list of type '(title: String, message: String, delegate:
MyViewController, cancelButtonTitle: String, otherButtonTitles:
String)'
As others mentioned, you should migrate to UIAlertController if you can target iOS 8.x+. To support iOS 7, use the code above (iOS 6 is not supported by Swift).
add a comment |
I got the following UIAlertView
initialization code to compile without errors (I thing the last, varyadic part is tricky perhaps). But I had to make sure the class of self
(which I am passing as the delegate) was adopting the UIAlertViewDelegate
protocol for the compile errors to go away:
let alertView = UIAlertView(
title: "My Title",
message: "My Message",
delegate: self,
cancelButtonTitle: "Cancel",
otherButtonTitles: "OK"
)
By the way, this is the error I was getting (as of Xcode 6.4):
Cannot find an initializer for type 'UIAlertView' that accepts an
argument list of type '(title: String, message: String, delegate:
MyViewController, cancelButtonTitle: String, otherButtonTitles:
String)'
As others mentioned, you should migrate to UIAlertController if you can target iOS 8.x+. To support iOS 7, use the code above (iOS 6 is not supported by Swift).
I got the following UIAlertView
initialization code to compile without errors (I thing the last, varyadic part is tricky perhaps). But I had to make sure the class of self
(which I am passing as the delegate) was adopting the UIAlertViewDelegate
protocol for the compile errors to go away:
let alertView = UIAlertView(
title: "My Title",
message: "My Message",
delegate: self,
cancelButtonTitle: "Cancel",
otherButtonTitles: "OK"
)
By the way, this is the error I was getting (as of Xcode 6.4):
Cannot find an initializer for type 'UIAlertView' that accepts an
argument list of type '(title: String, message: String, delegate:
MyViewController, cancelButtonTitle: String, otherButtonTitles:
String)'
As others mentioned, you should migrate to UIAlertController if you can target iOS 8.x+. To support iOS 7, use the code above (iOS 6 is not supported by Swift).
answered Jul 14 '15 at 7:44
Nicolas MiariNicolas Miari
10.3k552131
10.3k552131
add a comment |
add a comment |
The reason it doesn't work because some value you passed to the function isn't correct. swift doesn't like Objective-C, you can put nil to arguments which are class type without any restriction(might be). Argument otherButtonTitles is defined as non-optional which its type do not have (?)at its end. so you must pass a concrete value to it.
add a comment |
The reason it doesn't work because some value you passed to the function isn't correct. swift doesn't like Objective-C, you can put nil to arguments which are class type without any restriction(might be). Argument otherButtonTitles is defined as non-optional which its type do not have (?)at its end. so you must pass a concrete value to it.
add a comment |
The reason it doesn't work because some value you passed to the function isn't correct. swift doesn't like Objective-C, you can put nil to arguments which are class type without any restriction(might be). Argument otherButtonTitles is defined as non-optional which its type do not have (?)at its end. so you must pass a concrete value to it.
The reason it doesn't work because some value you passed to the function isn't correct. swift doesn't like Objective-C, you can put nil to arguments which are class type without any restriction(might be). Argument otherButtonTitles is defined as non-optional which its type do not have (?)at its end. so you must pass a concrete value to it.
edited Jun 29 '14 at 16:33
bpolat
3,0421223
3,0421223
answered Jun 28 '14 at 8:49
Oscar WuOscar Wu
314
314
add a comment |
add a comment |
@IBAction func Alert(sender: UIButton) {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Alert!"
alertView.message = "Message"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
Try this
add a comment |
@IBAction func Alert(sender: UIButton) {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Alert!"
alertView.message = "Message"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
Try this
add a comment |
@IBAction func Alert(sender: UIButton) {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Alert!"
alertView.message = "Message"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
Try this
@IBAction func Alert(sender: UIButton) {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Alert!"
alertView.message = "Message"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
Try this
answered Oct 13 '14 at 22:55
gskrilgskril
5615
5615
add a comment |
add a comment |
Use this code to display an alertview
let alertController = UIAlertController(title: "Hello Coders", message: "your alert message", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
Reference: Swift Show Alert using UIAlertController
add a comment |
Use this code to display an alertview
let alertController = UIAlertController(title: "Hello Coders", message: "your alert message", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
Reference: Swift Show Alert using UIAlertController
add a comment |
Use this code to display an alertview
let alertController = UIAlertController(title: "Hello Coders", message: "your alert message", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
Reference: Swift Show Alert using UIAlertController
Use this code to display an alertview
let alertController = UIAlertController(title: "Hello Coders", message: "your alert message", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
Reference: Swift Show Alert using UIAlertController
answered Oct 10 '16 at 2:47
Shaba AafreenShaba Aafreen
63744
63744
add a comment |
add a comment |
in xcode 9
let alert = UIAlertController(title: "Alert", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
add a comment |
in xcode 9
let alert = UIAlertController(title: "Alert", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
add a comment |
in xcode 9
let alert = UIAlertController(title: "Alert", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
in xcode 9
let alert = UIAlertController(title: "Alert", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
answered Oct 5 '17 at 6:34
luhuiyaluhuiya
8551113
8551113
add a comment |
add a comment |
let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .alert)
let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
print("Default is pressed.....")
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancel is pressed......")
}
let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
print("Destructive is pressed....")
}
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
add a comment |
let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .alert)
let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
print("Default is pressed.....")
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancel is pressed......")
}
let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
print("Destructive is pressed....")
}
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
add a comment |
let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .alert)
let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
print("Default is pressed.....")
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancel is pressed......")
}
let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
print("Destructive is pressed....")
}
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .alert)
let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
print("Default is pressed.....")
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancel is pressed......")
}
let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
print("Destructive is pressed....")
}
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
answered Mar 8 '18 at 9:28
Mr.Javed MultaniMr.Javed Multani
1
1
add a comment |
add a comment |
SWIFT 4 : Simply create a extension to UIViewController as follows:
extension UIViewController {
func showSuccessAlert(withTitle title: String, andMessage message:String) {
let alert = UIAlertController(title: title, message: message,
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK".localized, style:
UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Now in your ViewController, directly call above function as if they are provided by UIViewController.
yourViewController.showSuccessAlert(withTitle:
"YourTitle", andMessage: "YourCustomTitle")
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. Thanks for improving the answer's reference value and making it more understandable!
– Tim Diekmann
Jun 3 '18 at 13:58
add a comment |
SWIFT 4 : Simply create a extension to UIViewController as follows:
extension UIViewController {
func showSuccessAlert(withTitle title: String, andMessage message:String) {
let alert = UIAlertController(title: title, message: message,
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK".localized, style:
UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Now in your ViewController, directly call above function as if they are provided by UIViewController.
yourViewController.showSuccessAlert(withTitle:
"YourTitle", andMessage: "YourCustomTitle")
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. Thanks for improving the answer's reference value and making it more understandable!
– Tim Diekmann
Jun 3 '18 at 13:58
add a comment |
SWIFT 4 : Simply create a extension to UIViewController as follows:
extension UIViewController {
func showSuccessAlert(withTitle title: String, andMessage message:String) {
let alert = UIAlertController(title: title, message: message,
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK".localized, style:
UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Now in your ViewController, directly call above function as if they are provided by UIViewController.
yourViewController.showSuccessAlert(withTitle:
"YourTitle", andMessage: "YourCustomTitle")
SWIFT 4 : Simply create a extension to UIViewController as follows:
extension UIViewController {
func showSuccessAlert(withTitle title: String, andMessage message:String) {
let alert = UIAlertController(title: title, message: message,
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK".localized, style:
UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Now in your ViewController, directly call above function as if they are provided by UIViewController.
yourViewController.showSuccessAlert(withTitle:
"YourTitle", andMessage: "YourCustomTitle")
edited Dec 20 '18 at 17:09
Alex Nolasco
14k85862
14k85862
answered Jun 3 '18 at 13:37
Shikha BudhirajaShikha Budhiraja
615
615
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. Thanks for improving the answer's reference value and making it more understandable!
– Tim Diekmann
Jun 3 '18 at 13:58
add a comment |
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. Thanks for improving the answer's reference value and making it more understandable!
– Tim Diekmann
Jun 3 '18 at 13:58
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. Thanks for improving the answer's reference value and making it more understandable!
– Tim Diekmann
Jun 3 '18 at 13:58
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. Thanks for improving the answer's reference value and making it more understandable!
– Tim Diekmann
Jun 3 '18 at 13:58
add a comment |
try This.
Put Bellow Code In Button.
let alert = UIAlertController(title: "Your_Title_Text", message: "Your_MSG", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Your_Text", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated:true, completion: nil)
add a comment |
try This.
Put Bellow Code In Button.
let alert = UIAlertController(title: "Your_Title_Text", message: "Your_MSG", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Your_Text", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated:true, completion: nil)
add a comment |
try This.
Put Bellow Code In Button.
let alert = UIAlertController(title: "Your_Title_Text", message: "Your_MSG", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Your_Text", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated:true, completion: nil)
try This.
Put Bellow Code In Button.
let alert = UIAlertController(title: "Your_Title_Text", message: "Your_MSG", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Your_Text", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated:true, completion: nil)
edited Aug 2 '18 at 13:28
answered Dec 1 '17 at 8:00
Sagar SanganiSagar Sangani
955
955
add a comment |
add a comment |
SWIFT 4.X
let alert = UIAlertController(title: "user entered title", message: "user entered message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
print("Okay'd")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { action in
print("cancelled")
}))
self.present(alert, animated: true, completion: nil)
Added this to response to show how to do multiple actions (ie. OK / Cancel)
– Stotch
Jan 14 at 0:09
1
Don't post duplicate answers, please remove it...
– iOS
Jan 28 at 9:59
@Stotch Please don't post duplicate answer's, this answer already available in this question. Please post some different answer only not same type of answer. Please remove your answer....
– Marking
Jan 30 at 9:56
add a comment |
SWIFT 4.X
let alert = UIAlertController(title: "user entered title", message: "user entered message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
print("Okay'd")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { action in
print("cancelled")
}))
self.present(alert, animated: true, completion: nil)
Added this to response to show how to do multiple actions (ie. OK / Cancel)
– Stotch
Jan 14 at 0:09
1
Don't post duplicate answers, please remove it...
– iOS
Jan 28 at 9:59
@Stotch Please don't post duplicate answer's, this answer already available in this question. Please post some different answer only not same type of answer. Please remove your answer....
– Marking
Jan 30 at 9:56
add a comment |
SWIFT 4.X
let alert = UIAlertController(title: "user entered title", message: "user entered message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
print("Okay'd")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { action in
print("cancelled")
}))
self.present(alert, animated: true, completion: nil)
SWIFT 4.X
let alert = UIAlertController(title: "user entered title", message: "user entered message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
print("Okay'd")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { action in
print("cancelled")
}))
self.present(alert, animated: true, completion: nil)
answered Jan 14 at 0:09
StotchStotch
715
715
Added this to response to show how to do multiple actions (ie. OK / Cancel)
– Stotch
Jan 14 at 0:09
1
Don't post duplicate answers, please remove it...
– iOS
Jan 28 at 9:59
@Stotch Please don't post duplicate answer's, this answer already available in this question. Please post some different answer only not same type of answer. Please remove your answer....
– Marking
Jan 30 at 9:56
add a comment |
Added this to response to show how to do multiple actions (ie. OK / Cancel)
– Stotch
Jan 14 at 0:09
1
Don't post duplicate answers, please remove it...
– iOS
Jan 28 at 9:59
@Stotch Please don't post duplicate answer's, this answer already available in this question. Please post some different answer only not same type of answer. Please remove your answer....
– Marking
Jan 30 at 9:56
Added this to response to show how to do multiple actions (ie. OK / Cancel)
– Stotch
Jan 14 at 0:09
Added this to response to show how to do multiple actions (ie. OK / Cancel)
– Stotch
Jan 14 at 0:09
1
1
Don't post duplicate answers, please remove it...
– iOS
Jan 28 at 9:59
Don't post duplicate answers, please remove it...
– iOS
Jan 28 at 9:59
@Stotch Please don't post duplicate answer's, this answer already available in this question. Please post some different answer only not same type of answer. Please remove your answer....
– Marking
Jan 30 at 9:56
@Stotch Please don't post duplicate answer's, this answer already available in this question. Please post some different answer only not same type of answer. Please remove your answer....
– Marking
Jan 30 at 9:56
add a comment |
Here is a funny example in Swift:
private func presentRandomJoke() {
if let randomJoke: String = jokesController.randomJoke() {
let alertController: UIAlertController = UIAlertController(title:nil, message:randomJoke, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title:"Done", style:UIAlertActionStyle.Default, handler:nil))
presentViewController(alertController, animated:true, completion:nil)
}
}
add a comment |
Here is a funny example in Swift:
private func presentRandomJoke() {
if let randomJoke: String = jokesController.randomJoke() {
let alertController: UIAlertController = UIAlertController(title:nil, message:randomJoke, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title:"Done", style:UIAlertActionStyle.Default, handler:nil))
presentViewController(alertController, animated:true, completion:nil)
}
}
add a comment |
Here is a funny example in Swift:
private func presentRandomJoke() {
if let randomJoke: String = jokesController.randomJoke() {
let alertController: UIAlertController = UIAlertController(title:nil, message:randomJoke, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title:"Done", style:UIAlertActionStyle.Default, handler:nil))
presentViewController(alertController, animated:true, completion:nil)
}
}
Here is a funny example in Swift:
private func presentRandomJoke() {
if let randomJoke: String = jokesController.randomJoke() {
let alertController: UIAlertController = UIAlertController(title:nil, message:randomJoke, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title:"Done", style:UIAlertActionStyle.Default, handler:nil))
presentViewController(alertController, animated:true, completion:nil)
}
}
answered Apr 25 '15 at 6:51
ZorayrZorayr
15.1k29585
15.1k29585
add a comment |
add a comment |
Here is a pretty simple function of AlertView in Swift :
class func globalAlertYesNo(msg: String) {
let alertView = UNAlertView(title: "Title", message: msg)
alertView.messageAlignment = NSTextAlignment.Center
alertView.buttonAlignment = UNButtonAlignment.Horizontal
alertView.addButton("Yes", action: {
print("Yes action")
})
alertView.addButton("No", action: {
print("No action")
})
alertView.show()
}
You have to pass message as a String where you use this function.
add a comment |
Here is a pretty simple function of AlertView in Swift :
class func globalAlertYesNo(msg: String) {
let alertView = UNAlertView(title: "Title", message: msg)
alertView.messageAlignment = NSTextAlignment.Center
alertView.buttonAlignment = UNButtonAlignment.Horizontal
alertView.addButton("Yes", action: {
print("Yes action")
})
alertView.addButton("No", action: {
print("No action")
})
alertView.show()
}
You have to pass message as a String where you use this function.
add a comment |
Here is a pretty simple function of AlertView in Swift :
class func globalAlertYesNo(msg: String) {
let alertView = UNAlertView(title: "Title", message: msg)
alertView.messageAlignment = NSTextAlignment.Center
alertView.buttonAlignment = UNButtonAlignment.Horizontal
alertView.addButton("Yes", action: {
print("Yes action")
})
alertView.addButton("No", action: {
print("No action")
})
alertView.show()
}
You have to pass message as a String where you use this function.
Here is a pretty simple function of AlertView in Swift :
class func globalAlertYesNo(msg: String) {
let alertView = UNAlertView(title: "Title", message: msg)
alertView.messageAlignment = NSTextAlignment.Center
alertView.buttonAlignment = UNButtonAlignment.Horizontal
alertView.addButton("Yes", action: {
print("Yes action")
})
alertView.addButton("No", action: {
print("No action")
})
alertView.show()
}
You have to pass message as a String where you use this function.
answered Jun 15 '16 at 9:04
iAnkitiAnkit
1,5621522
1,5621522
add a comment |
add a comment |
The Old Way: UIAlertView
let alertView = UIAlertView(title: "Default Style", message: "A standard alert.", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alertView.alertViewStyle = .Default
alertView.show()
// MARK: UIAlertViewDelegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
// ...
}
}
The New Way: UIAlertController
let alertController = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
add a comment |
The Old Way: UIAlertView
let alertView = UIAlertView(title: "Default Style", message: "A standard alert.", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alertView.alertViewStyle = .Default
alertView.show()
// MARK: UIAlertViewDelegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
// ...
}
}
The New Way: UIAlertController
let alertController = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
add a comment |
The Old Way: UIAlertView
let alertView = UIAlertView(title: "Default Style", message: "A standard alert.", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alertView.alertViewStyle = .Default
alertView.show()
// MARK: UIAlertViewDelegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
// ...
}
}
The New Way: UIAlertController
let alertController = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
The Old Way: UIAlertView
let alertView = UIAlertView(title: "Default Style", message: "A standard alert.", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alertView.alertViewStyle = .Default
alertView.show()
// MARK: UIAlertViewDelegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
// ...
}
}
The New Way: UIAlertController
let alertController = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
answered Jul 4 '16 at 8:43
Shanmugasundharam selvaduraiShanmugasundharam selvadurai
1,6731627
1,6731627
add a comment |
add a comment |
on IOS 9, you can do this
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
add a comment |
on IOS 9, you can do this
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
add a comment |
on IOS 9, you can do this
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
on IOS 9, you can do this
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
answered Dec 28 '17 at 10:46
Keshav GeraKeshav Gera
2,9191828
2,9191828
add a comment |
add a comment |
// Generic Class For UIAlertView
//MARK:- MODULES
import Foundation
import UIKit
//MARK:- CLASS
class Alert : NSObject{
static let shared = Alert()
var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?
/** show */
public func show(title : String?, message : String?, viewController : UIViewController?, okAction : AlertSuccess = nil) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil);
}
}
/** showWithCancelAndOk */
public func showWithCancelAndOk(title : String, okTitle : String, cancelTitle : String, message : String, viewController : UIViewController?, okAction : AlertSuccess = nil, cancelAction : AlertSuccess = nil) {
let version:NSString = UIDevice.current.systemVersion as NSString;
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: cancelTitle, style: .default, handler: { (action: UIAlertAction) in
if let cancelAction = cancelAction {
cancelAction()
}
}))
alert?.addAction(UIAlertAction(title: okTitle, style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert!, animated:true, completion:nil);
}
}
/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when){
self.alert?.dismiss(animated: true, completion: nil)
}
}
}
}
Use:-
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self) //without ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}) // with ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}, cancelAction: {
//cancel action
}) //with cancel and ok action
Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self) //with timer
add a comment |
// Generic Class For UIAlertView
//MARK:- MODULES
import Foundation
import UIKit
//MARK:- CLASS
class Alert : NSObject{
static let shared = Alert()
var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?
/** show */
public func show(title : String?, message : String?, viewController : UIViewController?, okAction : AlertSuccess = nil) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil);
}
}
/** showWithCancelAndOk */
public func showWithCancelAndOk(title : String, okTitle : String, cancelTitle : String, message : String, viewController : UIViewController?, okAction : AlertSuccess = nil, cancelAction : AlertSuccess = nil) {
let version:NSString = UIDevice.current.systemVersion as NSString;
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: cancelTitle, style: .default, handler: { (action: UIAlertAction) in
if let cancelAction = cancelAction {
cancelAction()
}
}))
alert?.addAction(UIAlertAction(title: okTitle, style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert!, animated:true, completion:nil);
}
}
/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when){
self.alert?.dismiss(animated: true, completion: nil)
}
}
}
}
Use:-
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self) //without ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}) // with ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}, cancelAction: {
//cancel action
}) //with cancel and ok action
Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self) //with timer
add a comment |
// Generic Class For UIAlertView
//MARK:- MODULES
import Foundation
import UIKit
//MARK:- CLASS
class Alert : NSObject{
static let shared = Alert()
var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?
/** show */
public func show(title : String?, message : String?, viewController : UIViewController?, okAction : AlertSuccess = nil) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil);
}
}
/** showWithCancelAndOk */
public func showWithCancelAndOk(title : String, okTitle : String, cancelTitle : String, message : String, viewController : UIViewController?, okAction : AlertSuccess = nil, cancelAction : AlertSuccess = nil) {
let version:NSString = UIDevice.current.systemVersion as NSString;
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: cancelTitle, style: .default, handler: { (action: UIAlertAction) in
if let cancelAction = cancelAction {
cancelAction()
}
}))
alert?.addAction(UIAlertAction(title: okTitle, style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert!, animated:true, completion:nil);
}
}
/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when){
self.alert?.dismiss(animated: true, completion: nil)
}
}
}
}
Use:-
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self) //without ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}) // with ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}, cancelAction: {
//cancel action
}) //with cancel and ok action
Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self) //with timer
// Generic Class For UIAlertView
//MARK:- MODULES
import Foundation
import UIKit
//MARK:- CLASS
class Alert : NSObject{
static let shared = Alert()
var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?
/** show */
public func show(title : String?, message : String?, viewController : UIViewController?, okAction : AlertSuccess = nil) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil);
}
}
/** showWithCancelAndOk */
public func showWithCancelAndOk(title : String, okTitle : String, cancelTitle : String, message : String, viewController : UIViewController?, okAction : AlertSuccess = nil, cancelAction : AlertSuccess = nil) {
let version:NSString = UIDevice.current.systemVersion as NSString;
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: cancelTitle, style: .default, handler: { (action: UIAlertAction) in
if let cancelAction = cancelAction {
cancelAction()
}
}))
alert?.addAction(UIAlertAction(title: okTitle, style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert!, animated:true, completion:nil);
}
}
/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when){
self.alert?.dismiss(animated: true, completion: nil)
}
}
}
}
Use:-
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self) //without ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}) // with ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}, cancelAction: {
//cancel action
}) //with cancel and ok action
Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self) //with timer
answered Feb 28 '18 at 13:24
Pratyush PratikPratyush Pratik
517410
517410
add a comment |
add a comment |
// UIAlertView is deprecated. Use UIAlertController
// title = title of the alert view.
// message = Alert message you want to show.
// By tap on "OK" , Alert view will dismiss.
UIAlertView(title: "Alert", message: "Enter Message here.", delegate: nil, cancelButtonTitle: "OK").show()
Can you please add an explanation to the code you posted? As it is now, your answer does not really qualify as a good answer by SO rules.
– Nico Van Belle
May 4 '18 at 7:42
alert view has changed now in swift 4.use alert controller
– Sandeep Singh
May 15 '18 at 7:54
add a comment |
// UIAlertView is deprecated. Use UIAlertController
// title = title of the alert view.
// message = Alert message you want to show.
// By tap on "OK" , Alert view will dismiss.
UIAlertView(title: "Alert", message: "Enter Message here.", delegate: nil, cancelButtonTitle: "OK").show()
Can you please add an explanation to the code you posted? As it is now, your answer does not really qualify as a good answer by SO rules.
– Nico Van Belle
May 4 '18 at 7:42
alert view has changed now in swift 4.use alert controller
– Sandeep Singh
May 15 '18 at 7:54
add a comment |
// UIAlertView is deprecated. Use UIAlertController
// title = title of the alert view.
// message = Alert message you want to show.
// By tap on "OK" , Alert view will dismiss.
UIAlertView(title: "Alert", message: "Enter Message here.", delegate: nil, cancelButtonTitle: "OK").show()
// UIAlertView is deprecated. Use UIAlertController
// title = title of the alert view.
// message = Alert message you want to show.
// By tap on "OK" , Alert view will dismiss.
UIAlertView(title: "Alert", message: "Enter Message here.", delegate: nil, cancelButtonTitle: "OK").show()
edited May 4 '18 at 8:35
answered May 4 '18 at 7:03
Hitesh ChauhanHitesh Chauhan
720710
720710
Can you please add an explanation to the code you posted? As it is now, your answer does not really qualify as a good answer by SO rules.
– Nico Van Belle
May 4 '18 at 7:42
alert view has changed now in swift 4.use alert controller
– Sandeep Singh
May 15 '18 at 7:54
add a comment |
Can you please add an explanation to the code you posted? As it is now, your answer does not really qualify as a good answer by SO rules.
– Nico Van Belle
May 4 '18 at 7:42
alert view has changed now in swift 4.use alert controller
– Sandeep Singh
May 15 '18 at 7:54
Can you please add an explanation to the code you posted? As it is now, your answer does not really qualify as a good answer by SO rules.
– Nico Van Belle
May 4 '18 at 7:42
Can you please add an explanation to the code you posted? As it is now, your answer does not really qualify as a good answer by SO rules.
– Nico Van Belle
May 4 '18 at 7:42
alert view has changed now in swift 4.use alert controller
– Sandeep Singh
May 15 '18 at 7:54
alert view has changed now in swift 4.use alert controller
– Sandeep Singh
May 15 '18 at 7:54
add a comment |
1 2
next
protected by Nilesh Rathod Apr 18 '18 at 5:00
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
5
UIAlertView
andUIActionSheet
has been replaced byUIAlertController
in iOS 8, have you looked at this?– Popeye
Jun 3 '14 at 18:51
Make sure the class that
self
belongs to adopts the protocolUIAlertViewDelegate
(the recommended way to do this, in Swift, is with an extension).– Nicolas Miari
Jul 14 '15 at 7:37
@Adam: I have reverted your retagging. The swift3 tag is for "questions directly related to changes in version 3 of Apple's Swift programming language." And I don't think that "If the answers make it clear that the problem in the question was caused by something other than what the asker thought, retagging is very helpful." from meta.stackoverflow.com/questions/252079/… applies here.
– Martin R
Jul 13 '17 at 14:13
1
@MartinR I don't know how questions can be updated to show that there are answers that apply to a current version of Swift; there is a lot of old, useless stuff here and [swift] finds it all along with the useful. I don't feel strongly about this retag being reverted but I wish there was a definitive way to solve this problem. (I wish answers had tags.)
– Adam Eberbach
Jul 14 '17 at 0:50