ios 我将如何在 Swift 中创建 UIAlertView?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24022479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:19:47  来源:igfitidea点击:

How would I create a UIAlertView in Swift?

iosswiftcocoa-touchuialertviewuialertcontroller

提问by BlueBear

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:

我一直在努力在 Swift 中创建一个 UIAlertView,但由于某种原因,我无法正确使用该语句,因为我收到此错误:

Could not find an overload for 'init' that accepts the supplied arguments

找不到接受提供的参数的“init”的重载

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.

截至目前,它正在崩溃,我似乎无法正确使用语法。

回答by Oscar Swanros

From the UIAlertViewclass:

UIAlertView班级:

// UIAlertView is deprecated. Use UIAlertControllerwith a preferredStyle of UIAlertControllerStyleAlert instead

// UIAlertView 已弃用。使用UIAlertController和首选样式 UIAlertControllerStyleAlert 代替

On iOS 8, you can do this:

在 iOS 8 上,你可以这样做:

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 UIAlertControlleris a single class for creating and interacting with what we knew as UIAlertViews and UIActionSheets on iOS 8.

NowUIAlertController是一个单独的类,用于在 iOS 8 上创建我们所知道的UIAlertViews 和UIActionSheets并与之交互。

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:

为 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:

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

回答by Suragch

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: UIAlertAction.Style.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 handlerwas nilin the above examples. You can replace nilwith a closureto do something when the user taps a button. For example:

handlernil在上述实施例。当用户点击按钮时,您可以替换nil闭包以执行某些操作。例如:

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.Styletypes. They could all be .default.
  • For more than three buttons consider using an Action Sheet. The setup is very similar. Here is an example.
  • 多个按钮不一定需要使用不同的UIAlertAction.Style类型。他们都可以.default
  • 对于三个以上的按钮,请考虑使用操作表。设置非常相似。这是一个例子。

回答by Ben Gottlieb

You can create a UIAlert using the standard constructor, but the 'legacy' one seems to not work:

您可以使用标准构造函数创建 UIAlert,但“传统”构造函数似乎不起作用:

let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()

回答by iOS

In Swift 4.2 and Xcode 10

在 Swift 4.2 和 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)

}

Method 6:

方法六:

Alert in SharedClass with Extension

带扩展名的 SharedClass 中的警报

//This is your shared class
import UIKit

 class SharedClass: NSObject {

 static let sharedInstance = SharedClass()

 //Here write your code....

 private override init() {
 }
}

//Alert function in shared class
extension UIViewController {
    func showAlert(title: String, msg: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
}

Now call directly like this

现在直接这样调用

self.showAlert(title: "Your title here...", msg: "Your message here...")

Method 7:

方法七:

Alert with out shared class with Extension in separate classfor alert.

警报没有共享类,扩展名在单独的警报中。

Create one new Swift class, and import UIKit. Copy and paste below code.

创建一个新的 Swift 类,然后import UIKit. 复制并粘贴下面的代码。

//This is your Swift new class file
import UIKit
import Foundation

extension UIAlertController {
    class func alert(title:String, msg:String, target: UIViewController) {
        let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) {
        (result: UIAlertAction) -> Void in
        })
        target.present(alert, animated: true, completion: nil)
    }
}

Now call alert function like this in all your classes (Single line).

现在在所有类中调用这样的警报函数(单行)。

UIAlertController.alert(title:"Title", msg:"Message", target: self)

How is it....

如何....

回答by Hiren Patel

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

用两个按钮确定和取消完成

回答by AstroCB

If you're targeting iOS 7 and8, you need something like this to make sure you're using the right method for each version, because UIAlertViewis deprecated in iOS 8, but UIAlertControlleris not available in iOS 7:

如果你的目标是 iOS 78,你需要这样的东西来确保你为每个版本使用正确的方法,因为UIAlertView在 iOS 8 中被弃用,但UIAlertController在 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()
    }
}

回答by knshn

With the protocol extensions of Swift 2, you can make a protocol that provides a default implementation to your view controllers:

使用 Swift 2 的协议扩展,您可以创建一个协议,为您的视图控制器提供默认实现:

ShowsAlert.swift

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

视图控制器.swift

class ViewController: UIViewController, ShowsAlert {
    override func viewDidLoad() {
        super.viewDidLoad()
        showAlert(message: "Hey there, I am an error message!")
    }
}

回答by Peymankh

Simply do not provide otherButtonTitles in the constructor.

简单地不要在构造函数中提供 otherButtonTitles。

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.

但我确实同意 Oscar,这个类在 iOS 8 中已被弃用,因此如果您正在开发仅适用于 iOS 8 的应用程序,就不会使用 UIAlertView。否则上面的代码将起作用。

回答by Anit Kumar

Show UIAlertView in swift language :-

以快速语言显示 UIAlertView :-

Protocol UIAlertViewDelegate

协议 UIAlertViewDelegate

let alert = UIAlertView(title: "alertView", message: "This is alertView", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles: "Done", "Delete")
alert.show()

Show UIAlertViewController in swift language :-

以 swift 语言显示 UIAlertViewController :-

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)

回答by Mujah Maskey

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.

有人可以解释这一点。