【问题标题】:How would I create a UIAlertView in Swift?如何在 Swift 中创建 UIAlertView?
【发布时间】:2014-07-24 05:17:31
【问题描述】:

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

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

我是这样写的:

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

然后调用它我正在使用:

button2Alert.show()

到目前为止,它正在崩溃,我似乎无法正确使用语法。

【问题讨论】:

  • UIAlertViewUIActionSheet 在 iOS 8 中已被 UIAlertController 取代,你看过这个吗?
  • 确保self 所属的类采用UIAlertViewDelegate 协议(在Swift 中推荐的方法是使用扩展)。
  • @Adam:我已恢复您的重新标记。 swift3 标签用于 “与 Apple Swift 编程语言第 3 版更改直接相关的问题。” 而且我不认为 “如果答案清楚表明问题所在在问题是由提问者认为之外的其他原因引起的,重新标记非常有帮助。”来自meta.stackoverflow.com/questions/252079/…的应用在这里。
  • @MartinR 我不知道如何更新问题以表明存在适用于当前版本 Swift 的答案;这里有很多旧的、无用的东西,[swift] 发现它们和有用的东西一起。我对恢复这个重新标记的感觉并不强烈,但我希望有一个明确的方法来解决这个问题。 (我希望答案有标签。)

标签: ios swift cocoa-touch uialertview uialertcontroller


【解决方案1】:

来自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 上称为 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")
    }
}}))

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

【讨论】:

  • 您在哪里看到 UIAlertView 已被弃用?我在文档中没有看到?
  • Cmd + 点击UIAlertView类,注释就在类声明的正上方。
  • 我会为其他好奇的人回答我自己的问题 alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (ACTION :UIAlertAction!)in }) )
  • 取消和破坏性案例有什么意义,因为它始终是您指定的.Default
  • 阅读this 回答您所做的开关盒是不必要的。该开关仅在类型或标题没有硬编码时才有用,即它们是动态的: 您可能有一系列动态按钮,因此标题没有硬编码。然后处理程序可能需要将选择的标题传递给其他方法调用
【解决方案2】:

一个按钮

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

两个按钮

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

三个按钮

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.

【讨论】:

  • UIAlertController 中是否有任何委托属性?在 UIAlertView 中有一个委托属性,我们有时将其设置为 self,在 UIAlertController 中有没有这样的东西?我是新手,请帮帮我
  • 漂亮的答案 - 现在我们如何在处理程序中切换到新视图?
【解决方案3】:

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

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

【讨论】:

  • UIAlertView 已弃用。将 UIAlertController 与一个首选样式 UIAlertControllerStyleAlert 一起使用。
  • @Zorayr UIAlertController 仅从 iOS 8 开始可用,请在建议使用时提及。在某些情况下,仍然需要 iOS7 支持,人们可能会错过这个问题。弃用并不意味着“不再使用它”。
  • 如果您的应用程序仍然以 iOS 7 为目标,则此方法有效。但是,理想情况下,UIAlertView 应仅在 UIAlertController 不可用时使用。 if NSClassFromString("UIAlertController") != nil { /* 使用 UIAlertController * / } else { /* 使用 UIAlertView * / }
  • UIAlertview() 现在在 iOS 9 中已弃用
【解决方案4】:

在 Swift 4.2 和 Xcode 10 中

方法一:

简单提醒

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

方法二:

共享类警报

如果你想要共享类风格(写一次,到处使用)

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

方法三:

当前警报位于所有窗口的顶部

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

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

方法四:

带有扩展的警报

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

方法五:

文本字段提醒

如果您想在警报中添加文本字段。

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

方法六:

带有扩展的 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...")

方法七:

警报没有共享类,扩展在单独的类中用于警报。

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

怎么样……

【讨论】:

  • 完美! +1您能否添加一个集成超时的方法?谢谢!
  • @Passe,不好意思看不懂,能不能简单解释一下。
  • 我需要一个 alertController 直到单击“确定”按钮或发生超时。类似于方法 6 或 7,但有一个额外的输入变量“超时”。
  • 如果您在这种情况下提到 timeInterval 0 如果您不想关闭警报,请使用 if 条件。 if timeInterval != 0 { if #available(iOS 10.0, *) { Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false, block: { _ in alert.dismiss(animated: true, completion: nil) }) } else { // Fallback on earlier versions } }
  • 不错的解决方案。在方法 2 中,“SharedClass.SharedInstance...”必须是“SharedClass.sharedInstance...”。
【解决方案5】:

点击查看

@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 两个按钮完成

【讨论】:

  • 对我很有帮助。
【解决方案6】:

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

【讨论】:

  • 或者您可以节省时间并使用UIAlertView,直到您放弃对 iOS 7 的支持。Apple 不会因此拒绝您的应用。
  • 弃用并不意味着“不要使用这个”或者它会是“错误的方法”,它只是意味着它以后不会工作。如果只需要基本警报,则无需在 iOS8 上专门使用 UIAlertController。他们将像以前一样工作。许多 API 在 iOS4 或 5 中已被弃用,但在 iOS8 中仍然有效。但当然,针对更高 iOS 级别的应用不应使用它们,这就是为什么会有弃用警告。
  • @SamiKuhmonen 不,但它可以更清楚地说明您为什么要这样做,并且当您的最低版本足够高时可以更轻松地删除对已弃用方法的支持。跨度>
【解决方案7】:

使用 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!")
    }
}

【讨论】:

  • 完美运行。对于 Swift3,将“presentViewController”更改为“present”。
【解决方案8】:

以 Swift 语言显示 UIAlertView :-

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

【讨论】:

    【解决方案9】:

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

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

    但我同意 Oscar 的观点,这个类在 iOS 8 中已被弃用,所以如果你正在做一个仅限 iOS 8 的应用程序,那么 UIAlertView 将没有用处。否则上面的代码将起作用。

    【讨论】:

      【解决方案10】:

      我找到了这个,

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

      有人可以解释一下。

      【讨论】:

      • 显然 UIAlertView 在 iOS 8 中已被弃用,我们现在使用 UIAlertController 和 UIAlertControllerStyleAlert 的首选样式。
      • 如果您运行的应用程序需要向后兼容 iOS7.1,并且您使用 Swift 编写它,那么 UIAlertController 将使目标设备崩溃。您需要支持 iOS7 的旧版 UIAlertViews。
      • 我认为不是 Swift 会导致崩溃,而是 UIAlertController 在 iOS 8 之前不可用
      【解决方案11】:

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

      【讨论】:

        【解决方案12】:

        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)
        

        【讨论】:

          【解决方案13】:

          适用于 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 参数仅用于决定文本的颜色(以及按钮应该出现的一些默认顺序,哪些 ofc 可以更改)

          一个示例处理函数可以是

          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 操作按钮的完成处理程序。

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

          【讨论】:

          • 视图控制器上下文中的自身
          【解决方案14】:
              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")
                          }
                      }
                  }
              }
          

          【讨论】:

          • 只写一堆代码用处不大。在回答任何问题时(特别是一个包含多个答案的老问题,包括一个已接受的答案),请编写不止一段代码。请解释您的代码的作用、它如何回答问题以及它与其他答案有何不同(或更好)。
          【解决方案15】:

          我还有一个技巧。假设您有 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() 实现。希望对您有所帮助。

          【讨论】:

            【解决方案16】:

            我已经制作了一个单例类,以便在您的应用程序的任何地方使用它: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.")
            

            【讨论】:

            • 谢谢。我在那里提交了一些问题
            • 嘿@Swinny89 非常感谢您与我们分享这个解决方案!我被关闭的事情困住了,你刚刚救了我!
            【解决方案17】:

            斯威夫特 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、.破坏性和 .cancel。

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

            【讨论】:

              【解决方案18】:

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

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

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

              找不到接受“UIAlertView”类型的初始化程序 类型的参数列表'(标题:字符串,消息:字符串,委托: MyViewController,cancelButtonTitle:字符串,其他按钮标题: 字符串)'

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

              【讨论】:

                【解决方案19】:
                 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)
                
                }
                

                【讨论】:

                  【解决方案20】:

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

                  【讨论】:

                  • 请不要发布重复的答案。如果你想编辑你的答案。
                  • 优秀的答案。这就是我需要的。谢谢!
                  【解决方案21】:

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

                  【讨论】:

                    【解决方案22】:
                    @IBAction func Alert(sender: UIButton) {
                    
                        var alertView:UIAlertView = UIAlertView()
                        alertView.title = "Alert!"
                        alertView.message = "Message"
                        alertView.delegate = self
                        alertView.addButtonWithTitle("OK")
                    
                        alertView.show()
                    
                    }
                    

                    试试这个

                    【讨论】:

                      【解决方案23】:

                      使用此代码显示警报视图

                        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

                      【讨论】:

                        【解决方案24】:

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

                        【讨论】:

                          【解决方案25】:

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

                          【讨论】:

                          • 一般来说,如果答案包括对代码的用途的解释,以及为什么在不介绍其他人的情况下解决问题的原因,答案会更有帮助。感谢您提高答案的参考价值并使其更易于理解!
                          【解决方案26】:

                          或者只是这样做

                                  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)
                          

                          【讨论】:

                            【解决方案27】:

                            试试这个。 将波纹管代码放入按钮中。

                            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)
                            

                            【讨论】:

                              【解决方案28】:

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

                              【讨论】:

                                【解决方案29】:

                                这是一个非常简单的 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()
                                
                                    }
                                

                                您必须在使用此函数的地方将消息作为字符串传递。

                                【讨论】:

                                  【解决方案30】:

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

                                  【讨论】:

                                    猜你喜欢
                                    • 2011-08-05
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2016-10-22
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2019-02-24
                                    • 2014-08-18
                                    相关资源
                                    最近更新 更多