如何在全局swift中创builduialertcontroller

我正在尝试在Config.swift文件中创builduialertcontroller ,如下所示。

 static func showAlertMessage(titleStr:String, messageStr:String) -> Void { let window : UIWindow? let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.Alert); self.window!.presentViewController(alert, animated: true, completion: nil) } 

问题是我在self.window!.发现问题self.window!.

input'Config'没有成员'window'

请让我知道如何解决这个问题。

self.window意味着这个类有一个window对象,事实并非如此。

你需要使用你的let window : UIWindow? 使用window?.presentViewController(alert, animated: true, completion: nil) ,但这不会有帮助,因为这个窗口实际上并不代表任何现有的窗口,它不是视图控制器。

所以我build议你将实际的视图控制器传递给方法:

 static func showAlertMessage(vc: UIViewController, titleStr:String, messageStr:String) -> Void { let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.Alert); vc.presentViewController(alert, animated: true, completion: nil) } 

你可以从UIViewController对象可用的类中调用它。

这就是我使用的,这与@ penatheboss回答相同,只是增加了添加动作和处理程序的能力。

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

只要确保actionTitlesactions数组相同。 如果不需要任何操作处理程序closures,则通过

 self.popupAlert(title: "Title", message: " Oops, xxxx ", actionTitles: ["Option1","Option2","Option3"], actions:[{action1 in },{action2 in }, nil]) 

我build议创build一个扩展:

 extension UIViewController { func showAlertMessage(titleStr:String, messageStr:String) { let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.Alert) self.presentViewController(alert, animated: true, completion: nil) } } 

请参阅下面的GIT示例

https://github.com/amilaim/CommonAlertView

 // ViewController.swift // CommonAlertView // // Created by Amila Munasinghe on 4/25/17. // Copyright © 2017 Developer Insight. All rights reserved. // import UIKit class ViewController: UIViewController,AlertViewControllerDelegate { @IBOutlet weak var AlertViewResultTextOutlet: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func ShowAlertAction(_ sender: Any) { let alert = AlertViewController.sharedInstance alert.delegate = self alert.SubmitAlertView(viewController: self,title: "Developer Insight", message: "Please enter any text value") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func SubmitAlertViewResult(textValue : String) { AlertViewResultTextOutlet.text = textValue } } 

常见的UIAlertViewController实现

 import UIKit protocol AlertViewControllerDelegate { func SubmitAlertViewResult(textValue : String) } class AlertViewController { static let sharedInstance = AlertViewController() private init(){} var delegate : AlertViewControllerDelegate? func SubmitAlertView(viewController : UIViewController,title : String, message : String){ let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) // Submit button let submitAction = UIAlertAction(title: "Submit", style: .default, handler: { (action) -> Void in // Get 1st TextField's text let textField = alert.textFields![0] if(textField.text != "") { self.delegate?.SubmitAlertViewResult(textValue: textField.text!) } }) // Cancel button let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in }) // Add 1 textField and cutomize it alert.addTextField { (textField: UITextField) in textField.keyboardAppearance = .dark textField.keyboardType = .default textField.autocorrectionType = .default textField.placeholder = "enter any text value" textField.clearButtonMode = .whileEditing } // Add action buttons and present the Alert alert.addAction(submitAction) alert.addAction(cancel) viewController.present(alert, animated: true, completion: nil) } } 

我build议你写这个代码,但如果你真的需要,试试这个:

 static func showAlertMessage(titleStr:String, messageStr:String) -> Void { let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.Alert); if let viewController = UIApplication.sharedApplication().windows.first?.rootViewController as UIViewController? { viewController.presentViewController(alert, animated: true, completion: nil) } } 

至less它不会分解。

@Eric D更好的答案。

如果你想从AppDelegate窗口中呈现,你可以像这样使用

 UIApplication.sharedApplication().delegate?.window.rootViewController?.presentViewController(vc, animated: true, completion: nil) 

我创build了一个alerMessage类。我可以调用我的应用程序中的任何地方

 //Common Alert Message Class class AlertMessage { internal static var alertMessageController:UIAlertController! internal static func disPlayAlertMessage(titleMessage:String, alertMsg:String){ AlertMessage.alertMessageController = UIAlertController(title: titleMessage, message: alertMsg, preferredStyle: UIAlertControllerStyle.Alert) AlertMessage.alertMessageController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) if let controller = UIApplication.sharedApplication().keyWindow?.rootViewController?.presentedViewController { controller.presentViewController(AlertMessage.alertMessageController, animated: true, completion: nil) } else{ UIApplication.sharedApplication().delegate?.window!!.rootViewController?.presentViewController(AlertMessage.alertMessageController, animated: true, completion: nil) } return } } 

你可以试试这个,请在​​AppDelegate.swift文件中添加下面的代码。

  static func showAlertView(vc : UIViewController, titleString : String , messageString: String) ->() { let alertView = UIAlertController(title: titleString, message: messageString, preferredStyle: .alert) let alertAction = UIAlertAction(title: "ok", style: .cancel) { (alert) in vc.dismiss(animated: true, completion: nil) } alertView.addAction(alertAction) vc.present(alertView, animated: true, completion: nil) } 

并从任何视图控制器调用showAlertView方法

AppDelegate.showAlertView(vc:self,titleString:“testTitle”,messageString:“test msg”)

我使用的是@William Hu的解决scheme:

 func popup(caller:UIViewController, style:UIAlertControllerStyle? = UIAlertControllerStyle.alert, title:String, message:String, buttonTexts:[String], buttonStyles:([UIAlertActionStyle?])? = nil, handlers:[((UIAlertAction) -> Void)?], animated:Bool? = nil, completion: (() -> Void)? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: style!) for i in 0..<buttonTexts.count { alert.addAction(UIAlertAction(title: buttonTexts[i], style: (buttonStyles == nil || i >= buttonStyles!.count || buttonStyles![i] == nil ? UIAlertActionStyle.default : buttonStyles![i]!), handler: (i >= handlers.count || handlers[i] == nil ? nil : handlers[i]!))) } caller.present(alert, animated: animated != nil ? animated! : true, completion: completion) } 
  1. 单个函数默认提供Alert ,可以select用于ActionSheet
  2. 数组buttonStyles buttonTextsbuttonStyles buttonTextshandlers可以根据需要不相等的大小。
  3. Actions可以被设置。
  4. Animated可以指定。
  5. 演示完成后,可以指定可选block执行。

用法:

 popup(caller: self, style: UIAlertControllerStyle.alert, title: "Title", message: "Message", buttonTexts: ["Destructive", "Cancel", "OK"], buttonStyles: [UIAlertActionStyle.destructive, UIAlertActionStyle.cancel], handlers: [nil], animated: false)