How would I create a UIAlertView in Swift?

2019-01-01 11:52发布

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.

30条回答
呛了眼睛熬了心
2楼-- · 2019-01-01 12:24

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) {
 // ...
}
查看更多
倾城一夜雪
3楼-- · 2019-01-01 12:25

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).

查看更多
查无此人
4楼-- · 2019-01-01 12:25
 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)

}
查看更多
伤终究还是伤i
5楼-- · 2019-01-01 12:26

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")
查看更多
伤终究还是伤i
6楼-- · 2019-01-01 12:26

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)
查看更多
零度萤火
7楼-- · 2019-01-01 12:27

In Swift 4.2 and Xcode 9.4.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)
})

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")

PRESENT ALERT TOP 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")

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)

}
查看更多
登录 后发表回答