我该如何在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个回答

1

这里是一个有趣的 Swift 示例:

private func presentRandomJoke() {
  if let randomJoke: String = jokesController.randomJoke() {
    let alertController: UIAlertController = UIAlertController(title:nil, message:randomJoke, preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title:"Done", style:UIAlertActionStyle.Default, handler:nil))
    presentViewController(alertController, animated:true, completion:nil)
  }
}

1

以下是弹出提示框和操作表的可重用代码,只需写一行代码就可以在应用程序的任何地方显示提示框。

class AlertView{

    static func show(title:String? = nil,message:String?,preferredStyle: UIAlertControllerStyle = .alert,buttons:[String] = ["Ok"],completionHandler:@escaping (String)->Void){
        let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)

        for button in buttons{

            var style = UIAlertActionStyle.default
            let buttonText = button.lowercased().replacingOccurrences(of: " ", with: "")
            if buttonText == "cancel"{
                style = .cancel
            }
            let action = UIAlertAction(title: button, style: style) { (_) in
                completionHandler(button)
            }
            alert.addAction(action)
        }

        DispatchQueue.main.async {
            if let app = UIApplication.shared.delegate as? AppDelegate, let rootViewController = app.window?.rootViewController {
                rootViewController.present(alert, animated: true, completion: nil)
            }

        }
    }
}

使用方法:

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        AlertView.show(title: "Alert", message: "Are you sure ?", preferredStyle: .alert, buttons: ["Yes","No"]) { (button) in
            print(button)
        }
    }

}

1

对于13.0及以上版本 使用SceneDelegate

适用于所有种类的类

static func showWindowAlert(alertMessage: String, inVC:UIViewController) {
        DispatchQueue.main.async(execute: {
            guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                let sceneDelegate = windowScene.delegate as? SceneDelegate
              else {
                return
              }
            sceneDelegate.window?.rootViewController = inVC
            sceneDelegate.window?.windowLevel = UIWindow.Level.alert + 1
        
            let alert2 = UIAlertController(title: App_Name, message: alertMessage, preferredStyle: .alert)
            let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
            })
            alert2.addAction(defaultAction2)
        
            sceneDelegate.window?.makeKeyAndVisible()
        
            sceneDelegate.window?.rootViewController?.present(alert2, animated: true, completion: nil)
        })
    }

1

SwiftUI 在 Swift 5.x 和 Xcode 11.x 上运行。

import SwiftUI

struct ContentView: View {

    @State private var isShowingAlert = false

    var body: some View {
        VStack {
            Button("A Button") {

                self.isShowingAlert.toggle()
            }
            .alert(isPresented: $isShowingAlert) { () -> Alert in
                Alert(
                    title: Text("Alert"),
                    message: Text("This is an alert"),
                    dismissButton:
                        .default(
                            Text("OK"),
                            action: {
                                print("Dismissing alert")
                            }
                        )
                )
            }

        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

老兄,这是Swift UI,不是所要求的内容。 - Tilak Madichetti
2
是的,但由于我们将StackOverflow作为文档资源使用,我认为对于任何想要了解如何使用SwiftUI显示通知的人来说,这可能会很有用。我记得曾经很难找到答案,所以我想在这里发布并做出贡献。我认为这个问题更像是“如何在Swift应用程序中呈现警报”,而不是“如何仅使用UIKit呈现UIAlert”。 - gabriel_vincent

1

旧方法: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 {

    // ...
   }
  }

新的方式: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) {
 // ...
}

1
在iOS 9上,你可以这样做。
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)

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