如何在 Swift 中创建一个 UIAlertView?

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.

转载于:https://stackoverflow.com/questions/24022479/how-would-i-create-a-uialertview-in-swift

csdnceshi62
csdnceshi62 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.)
接近 3 年之前 回复
csdnceshi53
Lotus@ 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.
接近 3 年之前 回复
csdnceshi74
7*4 Make sure the class that self belongs to adopts the protocol UIAlertViewDelegate (the recommended way to do this, in Swift, is with an extension).
接近 5 年之前 回复
csdnceshi71
Memor.の UIAlertView and UIActionSheet has been replaced by UIAlertController in iOS 8, have you looked at this?
大约 6 年之前 回复

30个回答

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:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.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)
csdnceshi66
必承其重 | 欲带皇冠 yes agree switch case is not necessary
2 年多之前 回复
weixin_41568110
七度&光 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
3 年多之前 回复
weixin_41568110
七度&光 I think your example is a confusing one or at least that I don't understand it usefulness. The style of the action is already default. There is no reason for you to switch over it in your closure. It will ALWAYS go to default. Can you make your example more meaningful so that we would know why the closure takes action as a parameter?
3 年多之前 回复
csdnceshi55
~Onlooker completion is just a block (Void -> Void)? that is executed when the view controller is done presenting.
4 年多之前 回复
csdnceshi63
elliott.david Under what context, would the completion be not nil in self.presentViewController(alert, animated: true, completion: nil) . Any samples?
4 年多之前 回复
csdnceshi73
喵-见缝插针 What's the point of Cancel and Destructive cases since it will always be what you specified .Default?
接近 6 年之前 回复
csdnceshi67
bug^君 I'll answer my own question for anyone else who's curious alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (ACTION :UIAlertAction!)in }))
大约 6 年之前 回复
csdnceshi55
~Onlooker Cmd + Click the UIAlertView class, and the comment is right on top of the class declaration.
大约 6 年之前 回复
csdnceshi68
local-host Where did you see that UIAlertView is deprecated? I don't see that in the documentation?
大约 6 年之前 回复

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()
csdnceshi56
lrony* UIAlertview() is now deprecated in iOS 9
接近 5 年之前 回复
weixin_41568127
?yb? 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 * / }
大约 5 年之前 回复
csdnceshi53
Lotus@ 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."
5 年多之前 回复
csdnceshi72
谁还没个明天 UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.
5 年多之前 回复

One Button

One Button Screenshot

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

Two Button Alert Screenshot

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

enter image description here

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.
weixin_41568174
from.. 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
2 年多之前 回复

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)
weixin_41568183
零零乙 This answers the question directly and is correct
接近 5 年之前 回复

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.

csdnceshi60
℡Wang Yan 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
接近 6 年之前 回复
csdnceshi72
谁还没个明天 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.
大约 6 年之前 回复
csdnceshi56
lrony* Apparently UIAlertView has been deprecated in iOS 8 and we now use UIAlertController with a preferred style of UIAlertControllerStyleAlert.
大约 6 年之前 回复

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.")
csdnceshi52
妄徒之命 Hey @Swinny89 Thanks so much man for sharing this solution with us! I got stuck with the closure thing and you just saved me!
2 年多之前 回复
csdnceshi59
ℙℕℤℝ Thanks. I submit some issue there
4 年多之前 回复

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    
}

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

 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)

}

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

        }
    }
共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问