我该如何在Swift中创建一个UIAlertView?

555

我一直在努力使用Swift创建UIAlertView,但由于某种原因,我无法正确编写语句,因为我得到了这个错误:

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

以下是我的编写方式:

let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
                     delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)

然后我使用以下代码进行调用:

button2Alert.show()

截至目前它正在崩溃,我似乎无法正确地编写语法。


6
iOS 8中已经用UIAlertController替代了UIAlertView和UIActionSheet,你有看过吗?请注意不要改变原意。 - Popeye
请确保self所属的类采用了协议UIAlertViewDelegate(在Swift中,推荐的方法是使用扩展)。 - Nicolas Miari
@Adam:我已经恢复了您的重新标记。[tag:swift3]标签用于与苹果Swift编程语言第三版中的更改直接相关的问题。我认为来自https://meta.stackoverflow.com/questions/252079/tagging-a-question-based-on-its-answers的“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.”并不适用于这里。 - Martin R
1
@MartinR 我不知道如何更新问题以显示有适用于当前版本的Swift的答案;这里有很多旧的、无用的东西,[swift]与有用的东西一起找到了它们。我对这个重新标记被还原并没有强烈的感觉,但我希望有一个明确的方法来解决这个问题。(我希望答案有标签。) - Adam Eberbach
36个回答

4
您可以使用这个简单的扩展与n个按钮和相关操作在Swift4及以上版本中。
extension UIViewController {
    func popupAlert(title: String?, message: String?, actionTitles:[String?], actions:[((UIAlertAction) -> Void)?]) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        for (index, title) in actionTitles.enumerated() {
            let action = UIAlertAction(title: title, style: .default, handler: actions[index])
            alert.addAction(action)
        }
        self.present(alert, animated: true, completion: nil)
    }
}

你可以像这样使用它:
self.popupAlert(title: "Message", message: "your message", actionTitles: ["first","second","third"], actions:[
            {action1 in
                //action for first btn click
            },
            {action2 in
                //action for second btn click
            },
            {action3 in
                //action for third btn click
            }, nil]) 

请将以下与编程有关的内容从英语翻译为中文。仅返回已翻译的文本:请不要发布重复的答案。如果您想编辑您的答案,请这样做。 - Naresh
非常好的回答。这正是我需要的。谢谢! - Wide Angle Technology

3
@IBAction func Alert(sender: UIButton) {

    var alertView:UIAlertView = UIAlertView()
    alertView.title = "Alert!"
    alertView.message = "Message"
    alertView.delegate = self
    alertView.addButtonWithTitle("OK")

    alertView.show()

}

试试这个


3

SWIFT 4: 只需创建一个UIViewController的扩展,如下所示:

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

现在在您的ViewController中,直接调用上述函数,就像它们是由UIViewController提供的一样。

    yourViewController.showSuccessAlert(withTitle: 
      "YourTitle", andMessage: "YourCustomTitle")

通常情况下,如果答案包括代码的意图和解决问题的原因,而不会引入其他问题,那么这些答案会更有帮助。感谢您提高答案的参考价值并使其更易理解! - Tim Diekmann

3

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

3
使用以下代码显示一个警告框:
  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)

参考: 使用UIAlertController显示警告的Swift方法


3

这个函数无法工作的原因是你传递给它的某个值是不正确的。Swift 不喜欢 Objective-C,你可以在类型为 class 的参数中不加限制地放置 nil。但 otherButtonTitles 参数被定义为非可选项,其类型末尾没有 (?) 标识,因此你必须向它传递一个具体的值。


2

// 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)
        }
    }
}
}

使用:-
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

2

试一下。 将下面的代码放在按钮中。

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)

1

这里是一个使用Swift语言编写的非常简单的AlertView函数:

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

    }

你需要将消息作为字符串传递到使用此函数的位置。

1
  // 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()

你能否给你发布的代码添加一些解释说明呢?按照SO规则,现在的回答并不算是一个好的回答。 - Nico Van Belle
警告视图在Swift 4中已更改。请使用警告控制器。 - Sandeep Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接