How to Add Action to Uialertview in Swift (iOS 7)

How to add action to UIAlertView in Swift (iOS 7)

I tested your code and it is working fine for me it prints the respective result:

func showAlert(){
var createAccountErrorAlert: UIAlertView = UIAlertView()

createAccountErrorAlert.delegate = self

createAccountErrorAlert.title = "Oops"
createAccountErrorAlert.message = "Could not create account!"
createAccountErrorAlert.addButtonWithTitle("Dismiss")
createAccountErrorAlert.addButtonWithTitle("Retry")

createAccountErrorAlert.show()
}

func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){

switch buttonIndex{

case 1:
NSLog("Retry");
break;
case 0:
NSLog("Dismiss");
break;
default:
NSLog("Default");
break;
//Some code here..

}
}

It print dismiss when i click on dismiss button.

How to add action to UIAlertView in Swift (iOS 7)

I tested your code and it is working fine for me it prints the respective result:

func showAlert(){
var createAccountErrorAlert: UIAlertView = UIAlertView()

createAccountErrorAlert.delegate = self

createAccountErrorAlert.title = "Oops"
createAccountErrorAlert.message = "Could not create account!"
createAccountErrorAlert.addButtonWithTitle("Dismiss")
createAccountErrorAlert.addButtonWithTitle("Retry")

createAccountErrorAlert.show()
}

func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){

switch buttonIndex{

case 1:
NSLog("Retry");
break;
case 0:
NSLog("Dismiss");
break;
default:
NSLog("Default");
break;
//Some code here..

}
}

It print dismiss when i click on dismiss button.

How to add an action to a UIAlertView button using Swift iOS

The Swifty way is to use the new UIAlertController and closures:

    // Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)

// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}

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

// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)

Swift 3:

    // Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}

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

// Present the controller
self.present(alertController, animated: true, completion: nil)

How would I create a UIAlertView in Swift?

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 UIAlertViews and UIActionSheets 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)

How to add action to buttons in Alert in Swift

Is your clickedButtonAtIndex method calling? Put a breakpoint and debug the code.
You doesn't set the delegate of alertView.

@IBOutlet var statusLabelAlert : UILabel

var alertTest = UIAlertView()
alertTest.delegate = self //set the delegate of alertView

@IBAction func alertButton(sender : AnyObject) {

alertTest.message = "Select one!"
alertTest.addButtonWithTitle("1st")
alertTest.addButtonWithTitle("2nd")
alertTest.addButtonWithTitle("3rd")
alertTest.title = "Test Alert"
alertTest.show()

}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
switch buttonIndex{
case 0:
statusLabelAlert.text = "1st"
case 1:
statusLabelAlert.text = "2nd"
case 2:
statusLabelAlert.text = "3rd"
default:
statusLabelAlert.text = "error"
}

}

Using UIAlertView in swift for iOS 7.1+

Looks like you want UIAlertView to have a nice completion handler. I do not care for the delegate pattern when using them, so I have come up with my own extension:

UIAlertView Extension (Completion Handler)

// Used by objc_getAssociatedObject
private var UIAlertViewWrapperPropertyKey : UInt8 = 0

typealias AlertViewCompletionHandler = (alertView: UIAlertView, buttonIndex: Int) -> Void

extension UIAlertView
{
// MARK: - Associated Properties

private var wrapper : UIAlertViewWrapper?
{
get { return objc_getAssociatedObject(self, &UIAlertViewWrapperPropertyKey) as? UIAlertViewWrapper }
set { objc_setAssociatedObject(self, &UIAlertViewWrapperPropertyKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) }
}

// MARK - Convenience Initializers

convenience init(title: String?, message: String?, cancelButtonTitle: String?)
{
self.init(title: title, message: message, delegate: nil, cancelButtonTitle: cancelButtonTitle)
}

convenience init(title: String?, message: String?, cancelButtonTitle: String?, otherButtonTitles: String...)
{
self.init(title: title, message: message, delegate: nil, cancelButtonTitle: cancelButtonTitle)

for buttonTitle in otherButtonTitles { self.addButtonWithTitle(buttonTitle) }
}

// MARK: - Show with Completion Handler

func showWithCompletion(_ completionHandler: AlertViewCompletionHandler? = nil)
{
self.wrapper = UIAlertViewWrapper(completionHandler: completionHandler)
self.delegate = self.wrapper

self.show()
}

// MARK: - Show Class Methods

class func showWithTitle(title: String?, message: String?, cancelButtonTitle: String?, completionHandler: AlertViewCompletionHandler? = nil)
{
showWithTitle(title, message: message, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: nil, completionHandler: completionHandler)
}

class func showWithTitle(title: String?, message: String?, cancelButtonTitle: String?, otherButtonTitle: String?, completionHandler: AlertViewCompletionHandler? = nil)
{
let otherButtonTitles : [String]? = otherButtonTitle != nil ? [otherButtonTitle!] : nil

showWithTitle(title, message: message, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: otherButtonTitles, completionHandler: completionHandler)
}

class func showWithTitle(title: String?, message: String?, cancelButtonTitle: String?, otherButtonTitles: [String]?, completionHandler: AlertViewCompletionHandler? = nil)
{
let alertView = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelButtonTitle)

if let otherButtonTitles = otherButtonTitles
{
for buttonTitle in otherButtonTitles
{
alertView.addButtonWithTitle(buttonTitle)
}
}

alertView.showWithCompletion(completionHandler)
}
}

UIAlertViewWrapper (Private Class)

// Private class that handles delegation and completion handler (do not instantiate)
private final class UIAlertViewWrapper : NSObject, UIAlertViewDelegate
{
// MARK: - Completion Handlers

var completionHandler: AlertViewCompletionHandler?

// MARK: - Initializers

init(completionHandler: AlertViewCompletionHandler?)
{
self.completionHandler = completionHandler
}

// MARK: - UIAlertView Delegate

private func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)
{
completionHandler?(alertView: alertView, buttonIndex: buttonIndex)
}
}

Example Usage

// You can use class function to call the UIAlertView
UIAlertView.showWithTitle("Hello", message: "Hello World", cancelButtonTitle: "Okay") { alertView, buttonIndex in

// Do something when the alert view is clicked
}

// Or... you can instantiate one and use the showWithCompletion method

let yesNoMaybeAlertView = UIAlertView(title: "Choice", message: "Pick one", cancelButtonTitle: "No", otherButtonTitles: "Yes", "Maybe")

yesNoMaybeAlertView.showWithCompletion { alertView, buttonIndex in

switch buttonIndex
{
case 1: println("Yes")
case 2: println("Maybe")
default: println("No")
}
}

UIAlertView/UIAlertController iOS 7 and iOS 8 compatibility

The detection pattern is identical to the Objective-C style.

You need to detect whether the current active runtime has the ability to instantiate this class

if objc_getClass("UIAlertController") != nil {

println("UIAlertController can be instantiated")

//make and use a UIAlertController

}
else {

println("UIAlertController can NOT be instantiated")

//make and use a UIAlertView
}

Don't try and work out this based on the OS version. You need to detect abilities NOT OS.

EDIT

The original detector for this answer NSClassFromString("UIAlertController") fails under -O optimisation so its been changed to the current version which does work for Release builds

EDIT 2

NSClassFromString is working at all optimisations in Xcode 6.3/Swift 1.2

Adding a action to a UIAlert that takes the user to settings

Use this code . May be help it.

override func viewDidAppear(animated: Bool) {
var alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .Alert)

var settingsAction = UIAlertAction(title: "Settings", style: .Default) { (_) -> Void in
let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
if let url = settingsUrl {
UIApplication.sharedApplication().openURL(url)
}
}

var cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
alertController.addAction(settingsAction)
alertController.addAction(cancelAction)

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

Please note UIApplicationOpenSettingsURLString is only available on iOS8.0 and after so if your app should support iOS7 you'll have to check for availability of the constant (or if using Swift 2.0 use the #availability keyword).



Related Topics



Leave a reply



Submit