如何在全球范围内创建uialertcontroller

时间:2016-07-01 11:15:26

标签: ios swift uialertcontroller

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

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!.

中发现了问题
  

类型'Config'没有成员'window'

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

12 个答案:

答案 0 :(得分:27)

<强>迅速

这里是我使用的,这与@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数组的计数相同。如果您不需要任何操作处理程序关闭,请传递 nil

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

},{action2 in

}, nil])

目标C

添加UIViewController

的类别

<强>的UIViewController + PopAlert.h

#import <UIKit/UIKit.h>

@interface UIViewController (UIViewControllerCategory)
- (void) popAlertWithTitle: (NSString*) title message: (NSString*) message actionTitles:(NSArray *) actionTitles actions:(NSArray*)actions;
@end

<强>的UIViewController + PopAlert.m

#import "UIViewController+PopAlert.h"

@implementation UIViewController (UIViewControllerCategory)
- (void) popAlertWithTitle: (NSString*) title message: (NSString*) message actionTitles:(NSArray *) actionTitles actions:(NSArray*)actions {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [actionTitles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:obj style:UIAlertActionStyleDefault handler:actions[idx]];
        [alert addAction:action];
    }];
    [self presentViewController:alert animated:YES completion:nil];
}
@end

<强>用法

#import UIViewController+PopAlert.h

...

[super viewDidDisappear:animated];
    NSArray *actions = @[^(){NSLog(@"I am action1");}, ^(){NSLog(@"I am action2");}];
    [self popAlertWithTitle:@"I am title" message:@"good" actionTitles:@[@"good1", @"good2"] actions:actions];

答案 1 :(得分:17)

self.window意味着此类中有一个window对象,情况并非如此。

您需要将let window : UIWindow?window?.presentViewController(alert, animated: true, completion: nil)一起使用,但这无济于事,因为此窗口实际上并不代表任何现有窗口,而且无论如何它都不是视图控制器。

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

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对象可用的类中调用它。

答案 2 :(得分:4)

详细信息

  • Swift 5.1,Xcode 11.3.1

具有UIViewController扩展的全局UIAlertController

extension UIViewController{

    // Global Alert
    // Define Your number of buttons, styles and completion
    public func openAlert(title: String,
                          message: String,
                          alertStyle:UIAlertController.Style,
                          actionTitles:[String],
                          actionStyles:[UIAlertAction.Style],
                          actions: [((UIAlertAction) -> Void)]){

        let alertController = UIAlertController(title: title, message: message, preferredStyle: alertStyle)
        for(index, indexTitle) in actionTitles.enumerated(){
            let action = UIAlertAction(title: indexTitle, style: actionStyles[index], handler: actions[index])
            alertController.addAction(action)
        }
        self.present(alertController, animated: true)
    }
}

用法

警报

self.openAlert(title: "alert",
                      message: "add your message",
                      alertStyle: .alert,
                      actionTitles: ["Okay", "Cancel"],
                      actionStyles: [.default, .cancel],
                      actions: [
                          {_ in
                               print("okay click")
                          },
                          {_ in
                               print("cancel click")
                          }
                     ])

ActionSheet

self.openAlert(title: "actionsheet",
                  message: "add your message",
                  alertStyle: .actionSheet,
                  actionTitles: ["Okay", "Cancel"],
                  actionStyles: [.default, .cancel],
                  actions: [
                      {_ in
                           print("okay click")
                      },
                      {_ in
                           print("cancel click")
                      }
                 ])

答案 3 :(得分:2)

我建议创建扩展程序:

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

答案 4 :(得分:2)

您可以尝试此操作,请在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)

    }

并从任何viewcontroller调用 showAlertView 方法

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

答案 5 :(得分:1)

我创建了一个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

 }
}

答案 6 :(得分:1)

请参考下面的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)

 }

}

答案 7 :(得分:1)

您可以使用我在Swift4中为Show Alert创建的Utility类。它只需编写单行代码即可轻松使用:

显示简单提醒

@IBAction func showDefaultAlert(_ sender: Any) {

  Alert.showAlert(title:"Alert", message:"Default Alert")

}

演示代码链接: https://github.com/smindia1988/EasyAlertInSwift4

答案 8 :(得分:0)

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

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

至少它不会崩溃。

@Eric D更好的答案。

答案 9 :(得分:0)

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

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

答案 10 :(得分:0)

我根据@William Hu的解决方案使用的是什么:

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,并且可以选择用于ActionSheet
  2. 根据要求,阵列buttonTextsbuttonStyleshandlers的大小可能不相等。
  3. Actions可以设置样式。
  4. 可以指定
  5. Animated
  6. 可以指定在演示文稿完成时执行block
  7. 用法:

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

答案 11 :(得分:0)

这也是您可以在可用的View Controller之上显示的方式。

UIApplication.topViewController()?.present(alertViewController!, animated: true, completion: nil)