我如何在Swift中创建UIAlertView?

Blu*_*ear 462 cocoa-touch uialertview ios swift uialertcontroller

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

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

这是我写的方式:

let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
                     delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
Run Code Online (Sandbox Code Playgroud)

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

button2Alert.show()
Run Code Online (Sandbox Code Playgroud)

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

Osc*_*ros 861

来自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)
Run Code Online (Sandbox Code Playgroud)

现在UIAlertController是一个单独的类,用于在iOS 8上创建和交互我们所知道的UIAlertViews和UIActionSheets.

编辑:处理操作:

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")
    }
}}))
Run Code Online (Sandbox Code Playgroud)

编辑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)
Run Code Online (Sandbox Code Playgroud)

编辑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)
Run Code Online (Sandbox Code Playgroud)

  • Cmd +单击`UIAlertView`类,注释就在类声明的顶部. (9认同)
  • 取消和破坏性案例有什么意义,因为它总是你指定的`.Default`? (5认同)
  • 阅读[this](http://stackoverflow.com/a/40894219/5175709)回答您所做的开关案例是**不必要**.该开关仅在类型或标题未被硬编码时才有用,即它们是动态的:*您可能有一系列动态按钮,因此标题不是硬编码的.然后处理程序可能需要将所选标题传递给其他方法调用* (4认同)
  • 你在哪里看到UIAlertView被弃用了?我在文档中没有看到这一点? (3认同)
  • 我将回答我自己的问题,其中任何一个好奇的警告.addAction(UIAlertAction(标题:"取消",样式:UIAlertActionStyle.Cancel,处理程序:{(行动:UIAlertAction!)in})) (2认同)
  • 我认为你的例子令人困惑,或者至少我不理解它的用处.动作的风格已经是"默认".没有理由你在关闭时"切换"它.它总是会违约.你能否让你的例子更有意义,以便我们知道为什么闭包把`action`作为参数? (2认同)

Sur*_*gch 444

一键

单键截图

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

两个按钮

两个按钮警报截图

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

三个按钮

在此输入图像描述

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

处理按钮水龙头

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

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

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

}))
Run Code Online (Sandbox Code Playgroud)

笔记

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

  • UIAlertController中有任何委托属性吗?在UIAlertView中有一个委托属性,我们有时会设置为self,在UIAlertController中有没有这样的东西?我是新来的,请帮帮我 (2认同)

Ben*_*ieb 113

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

let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
Run Code Online (Sandbox Code Playgroud)

  • @Zorayr UIAlertController仅适用于iOS 8以上版本,请在提示使用时提及.有些情况下仍然需要iOS7支持,人们可能会错过这个问题.弃用并不意味着"不再使用它". (15认同)
  • UIAlertView已弃用.使用UIAlertController而不是UIAlertControllerStyleAlert的preferredStyle. (8认同)
  • 这适用于您的应用仍然以iOS 7为目标.但是,理想情况下,只有在UIAlertController不可用时才应使用UIAlertView.如果NSClassFromString("UIAlertController")!= nil {/*使用UIAlertController*/} else {/*使用UIAlertView*/} (2认同)

iOS*_*iOS 29

在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)
})
Run Code Online (Sandbox Code Playgroud)

方法2:

警告共享类别

如果你想要共享类的风格(写一次使用的地方)

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() {
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在每件商品中都会调出这样的提醒

SharedClass.SharedInstance.alert(view: self, title: "Your title here", message: "Your message here")
Run Code Online (Sandbox Code Playgroud)

方法3:

现在警告所有WINDOWS

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

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)
    })
}
Run Code Online (Sandbox Code Playgroud)

功能调用

SharedClass.sharedInstance.alertWindow(title:"This your title", message:"This is your message")
Run Code Online (Sandbox Code Playgroud)

方法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)
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

现在这样打电话

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

方法5:

与TEXTFIELDS一起提醒

如果要添加文本字段以提醒.

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

}
Run Code Online (Sandbox Code Playgroud)


Hir*_*tel 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")
  }))

}
Run Code Online (Sandbox Code Playgroud)

完成两个按钮确定并取消


Ast*_*oCB 12

如果你的目标是iOS 7 8,你需要这样的东西以确保你为每个版本使用正确的方法,因为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()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 弃用并不意味着"不要使用它"或者它将是"错误的方法",它只是意味着它以后不会起作用.如果只需要基本警报,则无需在iOS8上专门使用UIAlertController.他们将像以前一样工作.有许多API已在iOS4或5中弃用,仍可在iOS8中使用.但当然,针对较高iOS级别的应用不应使用它们,这就是弃用警告的原因. (2认同)

kns*_*shn 12

使用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)
    }
}
Run Code Online (Sandbox Code Playgroud)

ViewController.swift

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


Ani*_*mar 11

用快速语言显示UIAlertView: -

协议UIAlertViewDelegate

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

用快速语言显示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)
Run Code Online (Sandbox Code Playgroud)


Pey*_*nkh 11

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

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

alertView.show()
Run Code Online (Sandbox Code Playgroud)

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


Nit*_*tin 11

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)
Run Code Online (Sandbox Code Playgroud)


Muj*_*key 9

我找到了这个,

var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
Run Code Online (Sandbox Code Playgroud)

不好,但它的工作:)

更新:

但我在头文件中找到了:

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

有人可以解释一下.

  • 如果您运行的应用程序需要向后兼容iOS7.1并且您在Swift中编写它,则UIAlertController将使目标设备崩溃.您需要支持iOS7的传统UIAlertViews. (6认同)

emr*_*tem 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)
    }))
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以随时使用它:

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

        } else { //User has clicked on Cancel

        }
    }
Run Code Online (Sandbox Code Playgroud)


Til*_*ddy 6

对于 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)
Run Code Online (Sandbox Code Playgroud)

请注意,所有操作按钮在点击时关闭警报视图是一个基本性质。该style参数仅用于决定文本的颜色(以及按钮出现的一些默认顺序,哪些可以更改)

示例处理程序函数可以是

func handler(_ action: UIAlertAction) { 

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

}
Run Code Online (Sandbox Code Playgroud)

作为旁注,我想说,而不是制作 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)
Run Code Online (Sandbox Code Playgroud)

上面的代码适用于 iPhone,但会在 iPad 运行时崩溃,因为UIPopoverPresentationController它将负责警报,并且当时不会引用任何内容。因此,为了避免您必须提供以下代码块

if let pop = action.popoverPresentationController {

     let v = sender as! UIView 
     pop.sourceView = v 
     pop.sourceRect = v.bounds
 }
Run Code Online (Sandbox Code Playgroud)

同样,如果 iPad 在弹出窗口之外的任何地方点击将关闭它,并且.cancel将调用操作按钮的完成处理程序。

希望有所帮助:) 话虽如此,如果您有任何疑问,请在下方评论


Jay*_*iya 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")
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


A.G*_*A.G 5

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

File- New- Swift类 - 命名它.

添加以下内容:

public extension UIViewController
{

    func makeLogOutAlert()
    {
        var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)

        refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
            self.navigationController?.popToRootViewControllerAnimated(true)
        }))

        refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
            refreshAlert .dismissViewControllerAnimated(true, completion: nil)
        }))

        presentViewController(refreshAlert, animated: true, completion: nil)
    }
}
Run Code Online (Sandbox Code Playgroud)

使用:self.makeLogOutAlert()实现.希望能帮助到你.


Swi*_*y89 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
    }
}
Run Code Online (Sandbox Code Playgroud)

或弹出窗口,如下所示:

Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")
Run Code Online (Sandbox Code Playgroud)


小智 5

斯威夫特3

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

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

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

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

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