Ios 如何在Swift中创建UIAlertView?

Ios 如何在Swift中创建UIAlertView?,ios,swift,cocoa-touch,uialertview,uialertcontroller,Ios,Swift,Cocoa Touch,Uialertview,Uialertcontroller,我一直在努力在Swift中创建UIAlertView,但由于某些原因,我无法获得正确的语句,因为我遇到了以下错误: 找不到接受所提供内容的“init”的重载 论据 我是这样写的: let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message", delegate: self, cancelButtonTitle: "OK", otherButtonTitles:

我一直在努力在Swift中创建UIAlertView,但由于某些原因,我无法获得正确的语句,因为我遇到了以下错误:

找不到接受所提供内容的“init”的重载 论据

我是这样写的:

let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
                     delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
那么我用的是:

button2Alert.show()

到目前为止,它正在崩溃,我似乎无法正确理解语法

UIAlertView
类:


//UIAlertView已弃用。将UIAlertController与 首选UIAlertControllerStyleAlert的样式

在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上的
UIAlertView
s和
UIActionSheet
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)
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)
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()

    }
为Swift 4.x编辑:

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

    }

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

let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
我找到了这个

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

可能有人可以解释这一点。

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

用swift语言显示UIAlertView:-

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)
协议UIAlertViewDelegate

let alert = UIAlertView(title: "alertView", message: "This is alertView", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles: "Done", "Delete")
alert.show()
以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)

试试这个

只需在构造函数中不提供其他按钮即可

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

alertView.show()
但我同意Oscar的观点,这个类在iOS 8中已经被弃用了,所以如果你只使用iOS 8应用程序,UIAlertView就没有用了。否则,上面的代码将起作用。

如果您的目标是iOS 7和iOS 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()
    }
}

以下是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)
  }
}

点击查看

@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&Cancel我得到了以下
UIAlertView
初始化代码,可以无错误地编译(我认为最后的varyadic部分可能很棘手)。但是我必须确保
self
类(我作为代理传递)采用了
UIAlertViewDelegate
协议来消除编译错误:

    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")
                }
            }
        }
    }
let alertView = UIAlertView(
                  title: "My Title",
                  message: "My Message",
                  delegate: self,
                  cancelButtonTitle: "Cancel",
                  otherButtonTitles: "OK"
                )
顺便说一下,这是我得到的错误(从Xcode 6.4开始):

找不到接受 类型为“”的参数列表(标题:字符串、消息:字符串、委托: MyViewController,取消按钮:字符串,其他按钮: 字符串)'


正如其他人提到的,如果可以将iOS 8.x+作为目标,那么应该迁移到UIAlertController。要支持iOS 7,请使用上面的代码(iOS 6不受Swift支持)。

我还有一个窍门。假设有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)
    }
}

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

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

斯威夫特酒店

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!")
    }
}
一键

两个按钮

三个按钮

操作按钮轻敲 在上述示例中,
处理程序
nil
。当用户点击按钮时,您可以将
nil
替换为todo。例如:

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

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

}))
笔记
  • 多个按钮不一定需要使用不同的
    UIAlertAction.Style
    类型。它们都可以是
    .default
  • 对于超过三个按钮,请考虑使用一个动作表。设置非常相似
我制作了一个singleton类,以方便您在应用程序中的任何位置使用:

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

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.")
或带有如下单个按钮的弹出窗口:

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

以下是Swift中AlertView的一个非常简单的功能:

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

    }

在使用此函数时,必须以字符串形式传递消息。

旧方法: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) {
 // ...
}

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    
}

使用此代码显示alertview

  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)
参考:

在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)
试试这个。 在按钮中输入以下代码

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)

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

对于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

        }
    }

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

在Swift 4.2和Xcode 10中

方法1:

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

    }
简单警报

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:

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

    }
共享类警报

如果您想要共享类样式(编写一次,在任何地方使用)

现在,在每个软件中都可以这样调用警报

SharedClass.sharedInstance.alert(view: self, title: "Your title here", message: "Your message here")
方法3:<
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]) 
// 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)
func handler(_ action: UIAlertAction) { 

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

}
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)
if let pop = action.popoverPresentationController {

     let v = sender as! UIView 
     pop.sourceView = v 
     pop.sourceRect = v.bounds
 }
        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)