我如何在Swift中创建UIAlertView?

时间:2014-06-03 18:35:19

标签: ios swift cocoa-touch uialertview uialertcontroller

我一直在努力在Swift中创建一个UIAlertView,但由于某些原因我无法得到正确的声明,因为我收到了这个错误:

  

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

以下是我写的方式:

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

然后打电话给我我正在使用:

button2Alert.show()

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

36 个答案:

答案 0 :(得分:829)

来自UIAlertView班级:

  

//不推荐使用UIAlertView。使用 UIAlertController   而不是UIAlertControllerStyleAlert的preferredStyle

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

现在UIAlertController是一个单独的类,用于在iOS 8上创建和我们所知的UIAlertViewUIActionSheet s。

编辑:要处理操作:

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

编辑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)

编辑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)

答案 1 :(得分:414)

一个按钮

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

三个按钮

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

处理按钮点击

以上示例中的handlernil。当用户点按按钮时,您可以将nil替换为closure来执行某些操作。例如:

alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: { action in

    // do something like...
    self.launchMissile()

}))

注释

  • 多个按钮不一定需要使用不同的UIAlertAction.Style类型。它们都可以是.default
  • 对于三个以上的按钮,请考虑使用操作表。设置非常相似。 Here is an example.

答案 2 :(得分:113)

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

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

答案 3 :(得分:23)

在Swift 4.2和Xcode 10中

方法1:

简单提醒

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

方法2:

具有共享类的ALERT

如果您要使用共享类样式(在每个位置写入一次)

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

现在在每个商品中都这样的呼叫提醒

SharedClass.SharedInstance.alert(view: self, title: "Your title here", message: "Your message here")

方法3:

所有窗口的当前警报顶部

如果要在所有视图顶部显示警报,请使用此代码

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

函数调用

SharedClass.sharedInstance.alertWindow(title:"This your title", message:"This is your message")

方法4:

扩展通知

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

现在这样通话

//Call showAlert function in your class
@IBAction func onClickAlert(_ sender: UIButton) {
    showAlert(withTitle:"Your Title Here", withMessage: "YourCustomMessageHere")
}

方法5:

带有文本字段的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)

}

方法6:

带有扩展名的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)
        }
    }
}

现在直接像这样呼叫

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

方法7:

与扩展程序在单独的类中没有共享类的警报

创建一个新的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)
    }
}

现在在您所有的类中(单行)都具有这样的呼叫提醒功能。

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

怎么样......

答案 4 :(得分:18)

点击查看

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

}

用两个按钮完成OK&取消

答案 5 :(得分:12)

如果你的目标是iOS 7 8,那么你需要这样的东西,以确保你为每个版本使用正确的方法,因为在iOS 8中不推荐使用UIAlertView ,但在iOS 7中无法使用UIAlertController

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

答案 6 :(得分:11)

用快速语言显示UIAlertView: -

协议UIAlertViewDelegate

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

用快速语言显示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)

答案 7 :(得分:11)

只是不要在构造函数中提供otherButtonTitles。

let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")

alertView.show()

但我确实同意奥斯卡,这个类在iOS 8中已被弃用,因此如果您只使用iOS 8应用,则不会使用UIAlertView。否则上面的代码将起作用。

答案 8 :(得分:11)

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

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

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

答案 9 :(得分:9)

我找到了这个,

var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();

虽然不好,但确实有效:)

更新

但我在头文件中找到了:

extension UIAlertView {
    convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}

有人可以解释一下。

答案 10 :(得分:7)

对于 SWIFT4 ,我认为,扩展UIViewController并创建可重复使用的确认控件是最优雅的方式。

您可以扩展UIViewController,如下所示:

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

然后你可以随时使用它:

 AskConfirmation(title: "YOUR MESSAGE TITLE", message: "YOUR MESSAGE") { (result) in
        if result { //User has clicked on Ok

        } else { //User has clicked on Cancel

        }
    }

答案 11 :(得分:5)

Swift 3

以下是如何使用Swift 3的一个按钮创建简单警报的简单示例。

let alert = UIAlertController(title: "Title",
                              message: "Message",
                              preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)

在上面的示例中,操作的句柄回调已被省略,因为单击按钮时,带有一个按钮的警报视图的默认行为将消失。

以下是如何创建另一个操作,可以使用“alert.addAction(action)”将其添加到警报中。不同的样式是.default,.destructive和.cancel。

let action = UIAlertAction(title: "Ok", style: .default) { action in
    // Handle when button is clicked    
}

答案 12 :(得分:5)

我制作了一个单身人士课程,方便您在应用中的任何位置使用:https://github.com/Swinny1989/Swift-Popups

然后,您可以创建一个包含多个按钮的弹出窗口,如下所示:

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

或弹出一个按钮,如下所示:

Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")

答案 13 :(得分:5)

    class Preview: UIViewController , UIAlertViewDelegate
    {
        @IBAction func MoreBtnClicked(sender: AnyObject)
        {
            var moreAlert=UIAlertView(title: "Photo", message: "", delegate: self, cancelButtonTitle: "No Thanks!", otherButtonTitles: "Save Image", "Email", "Facebook", "Whatsapp" )
            moreAlert.show()
            moreAlert.tag=111;
        }

        func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int)
        {
            if alertView.tag==111
            {
                if buttonIndex==0
                {
                    println("No Thanks!")
                }
                else if buttonIndex==1
                {
                    println("Save Image")
                }
                else if buttonIndex == 2
                {
                    println("Email")
                }
                else if buttonIndex == 3
                {
                    println("Facebook")
                }
                else if buttonIndex == 4
                {
                    println("Whatsapp")
                }
            }
        }
    }

答案 14 :(得分:5)

我有另一招。假设您有5个类,其中要应用注销警报。尝试使用swift类扩展。

File- New- Swift类 - 命名它。

添加以下内容:

#include <fstream>
#include <sstream>

#include "DDImage/Knobs.h"
#include "DDImage/DDMath.h"
#include "DDImage/ViewerContext.h"
#include "DDImage/Iop.h"
#include "DDImage/PixelIop.h"
#include "DDImage/Row.h"

using namespace DD::Image;

////////////////////////////////////////////////////////////////
/// GPU File Shader Op.

class GPUFileShader : public DD::Image::PixelIop
{

    const char* shaderFile_;
    std::string currShaderFile_;
    std::string shader_;
    int version_;
    int currVersion_;

    const char* gpuEngine_body() const
    {
        return shader_.c_str();
    }

    void pixel_engine(const Row& in, int y, int x, int r, ChannelMask channels, Row& out)
    {
        foreach(z, channels) {
            const float* inptr = in[z] + x;
            const float* END = inptr + (r - x);
            float* outptr = out.writable(z) + x;
            while (inptr < END)
                *outptr++ = *inptr++;
        }
    }

    void in_channels(int, DD::Image::ChannelSet& c) const { } // return c unchanged

public:
    GPUFileShader(Node* node)
        : PixelIop(node)
        , shaderFile_(0)
        , version_(0)
        , currVersion_(0)
    { }

    void knobs(Knob_Callback f)
    {
        File_knob(f, &shaderFile_, "shader_file", "OpenGL Shading Language file");
    }

    void _validate(bool)
    {
        if (!shaderFile_)
            return;

        if (version_ != currVersion_ || currShaderFile_ != std::string(shaderFile_)) {
            std::ifstream ifs(shaderFile_);
            if (!ifs) {
                Iop::error("Error reading shader file.");
                return;
            }
            std::stringstream str;
            std::copy(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>(), std::ostreambuf_iterator<char>(str));
            shader_ = str.str();
            currVersion_ = version_;
            currShaderFile_.assign(shaderFile_);
        }

        copy_info(0);
    }

    static const DD::Image::Op::Description d;
    const char* Class() const { return d.name; }
    const char* node_help() const { return "GPU Op which gets initialised from a file. Customise for proprietary formats. Default assumes OpenGL shading language code."; }

};

static Op* GPUFileShader_c(Node* node) { return new GPUFileShader(node); }
const Op::Description GPUFileShader::d("GPUFileShader", GPUFileShader_c);

使用:self.makeLogOutAlert()实现。希望它有所帮助。

答案 15 :(得分:4)

我得到了以下UIAlertView初始化代码来编译而没有错误(我最后一点,变量部分也许很棘手)。但是我必须确保self的类(我作为委托传递)正在采用UIAlertViewDelegate协议来消除编译错误:

let alertView = UIAlertView(
                  title: "My Title",
                  message: "My Message",
                  delegate: self,
                  cancelButtonTitle: "Cancel",
                  otherButtonTitles: "OK"
                )

顺便说一句,这是我得到的错误(从Xcode 6.4开始):

  

找不到接受的“UIAlertView”类型的初始值设定项   类型'的参数列表(标题:字符串,消息:字符串,委托:   MyViewController,cancelButtonTitle:String,otherButtonTitles:   字符串)'

正如其他人提到的,如果你可以定位iOS 8.x +,你应该迁移到UIAlertController。要支持iOS 7,请使用上面的代码(Swift不支持iOS 6)。

答案 16 :(得分:4)

 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)

}

答案 17 :(得分: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)

参考:Swift Show Alert using UIAlertController

答案 18 :(得分: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)

答案 19 :(得分:3)

@IBAction func Alert(sender: UIButton) {

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

    alertView.show()

}

试试这个

答案 20 :(得分:3)

它不起作用的原因是因为传递给函数的某些值不正确。 swift不喜欢Objective-C,你可以将nil设置为没有任何限制的类类型的参数(可能是)。参数otherButtonTitles定义为非可选的,其类型在其末尾没有(?)。所以你必须传递一个具体的值。

答案 21 :(得分: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")

答案 22 :(得分:2)

试试这个。 把Bellow代码放在按钮中。

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)

答案 23 :(得分:2)

SWIFT 4.X

    let alert = UIAlertController(title: "user entered title", message: "user entered message", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        print("Okay'd")
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { action in
        print("cancelled")
    }))
    self.present(alert, animated: true, completion: nil)

答案 24 :(得分:1)

或者只是这样做

        let alert = UIAlertController(title: "Alert", message: "Saved Successfully", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil)

答案 25 :(得分:1)

AlertView Swift 5及更高版本:-

let alert = UIAlertController(title: LocalizedStringConstant.alert, message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Retry", style: .cancel, handler: { (_) in })) self.present(alert, animated: true, completion: nil)

答案 26 :(得分:1)

对于iOS 13 Xcode 11+ Swift 5.X

UIAlertController现在可以提供警报以及操作表

警报

// First instantiate the UIAlertController

let alert = UIAlertController(title: "Title",
                              message: "Message ?",
                              preferredStyle: .alert)


 // Add action buttons to it and attach handler functions if you want to 

 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
 alert.addAction(UIAlertAction(title: "Just Do It!", style: .destructive, handler: nil))
 alert.addAction(UIAlertAction(title: "Maybe", style: .default, handler: nil))

// Show the alert by presenting it

self.present(alert, animated: true)

请注意,这是所有操作按钮在被点击时关闭警报视图的基本特征。 style参数仅用于确定文本的颜色(以及一些默认的显示按钮顺序,按钮的显示顺序可以更改)

示例处理程序函数可能是

func handler(_ action: UIAlertAction) { 

   if action.title == 'Title' {
       // do stuff
   }

}

作为一个补充说明,我可以说不用制作3个不同的处理程序,而只需制作1个并追溯到以上述方式激发它的元素即可。 我们也可以检查alert.style,但同样可以有多个.default样式的动作,我不建议

操作表

解释类似,因为此处的主要区别在于 警报会打断用户,而操作表会从iPhone的底部滑动 ,并在其中弹出iPad

操作表的目的是指导用户根据其当前状态决定其操作。因此,您必须像十字路口一样对待操作单!通常没有消息,标题显示为字幕大小的文本

let action = UIAlertController(title: "What do you want to do with the message",
                               message: nil,
                               preferredStyle: .actionSheet)

action.addAction(UIAlertAction(title: "Cancel", style: .cancel)) 

for act in ["Save", "Post", "Discard"] {  
          action.addAction(UIAlertAction(title: act, style: .default, handler: nil))
}

self.present(action, animated: true)

上面的代码将在iPhone上运行,但 在iPad上将在运行时崩溃 ,因为UIPopoverPresentationController将负责警报,那时它不会引用任何东西。因此,为避免这种情况,您必须提供以下代码段其必填项

if let pop = action.popoverPresentationController {

     let v = sender as! UIView 
     pop.sourceView = v 
     pop.sourceRect = v.bounds
 }

如果iPad在弹窗之外的任何地方点击都会将其关闭,并调用.cancel动作按钮的完成处理程序。

希望有帮助:)话虽如此,如果您有任何疑问,请在下面写下来

答案 27 :(得分:1)

下面是警报视图和操作表的可重用代码,只需编写一行即可在应用程序中的任何地方显示警报

pic = QLabel(self)
pic.setPixmap(QtGui.QPixmap('escudo.gif'))
pic.setFixedWidth(250)
pic.setFixedHeight(250)

用法:

pic.setMaximumWidth(250)
pic.setMaximumHeight(250)

答案 28 :(得分:1)

{'Coca Cola': [1.5, 'drinks'], 'Sprite': [1.5, 'drinks'], 'Apple Juice': [2.5, 'drinks'], 'Orange juice': [2.5, 'drinks'], 'Grape Juice': [2.5, 'drinks']}

答案 29 :(得分:1)

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

答案 30 :(得分: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)

答案 31 :(得分: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)
  }
}

答案 32 :(得分: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) {
 // ...
}

答案 33 :(得分: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()

    }

您必须将消息作为字符串传递给您使用此功能。

答案 34 :(得分:0)

您可以将此简单扩展程序与 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]) 

答案 35 :(得分:0)

在Swift 5.x和Xcode 11.x上

SwiftUI

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