2016-07-01 2 views
4

uialertcontrollerConfig.swiftファイルに作成しようとしています。グローバルスウィフトでuialertcontrollerを作成する方法

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

にタイプ「コンフィグ」は何のメンバー「窓」

を持っていない問題を見つけたです。

+1

私はタイプ・ビュー・コントローラの別の引数を追加し、そのコントローラを使用してアラートを提示します。 – Desdenova

+1

あなたはパラメータとしてプレゼンターも要求する必要があります。 – holex

答えて

9

self.windowは、このクラスにwindowオブジェクトが存在することを意味しますが、そうではありません。

window?.presentViewController(alert, animated: true, completion: nil)let window : UIWindow?を使用する必要がありますが、このウィンドウは実際には既存のウィンドウを表すものではなく、ビューコントローラーではないため、これは役に立ちません。

だから私はあなたが方法に使用することがあります実際のビューコントローラ渡し勧め:

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オブジェクトが利用可能であるクラスからそれを呼び出します。

+0

が見つかりました。エラー:https://postimg.org/image/xs5dhx3gx/ – ppshein

+0

Xcodeを更新してください。プロジェクトをクリーンアップします。 UIKitがインポートされていることを確認します。 – Moritz

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

は、少なくともそれがブレークダウンしません。

@エリックDの方が良い答えです。

0

あなたはこの

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

のように使用することができますAppDelegateの窓から提示したい場合は、私は拡張を作成勧め:

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

この行も追加してください... alert.addAction(UIAlertAction(title: "Ok"、style:.cancel、handler:nil)) –

+0

@ kishan94これはプログラマの選択に依存しています。警告 – penatheboss

0

私はalerMessageクラス.Iを作成することは、私の中の任意の場所を呼び出すことができますアプリケーション

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

} 
} 
13

これは私が使用したものです。これは@penathebossと同じですが、t彼はアクションとハンドラーを追加する能力を持っています。

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]) 
+1

素晴らしい解決策!これをGlobals.swiftに配置し、どのView Controllerからでも呼び出すことができます。 +1 –

+2

ありがとう、編集可能なアクションスタイルも追加しました。 'func popupAlert(title:String ?, message:String ?, actionTitles:[String?]、actionStyles:[Int?]、actions :((UIAlertAction)actionTitles:["Option1"、 "Option2"、 "Option3"]、 actionsStyles:[無効]をクリックすると、 UIAlertActionStyle.destructive.rawValue、UIAlertActionStyle.default.rawValue ,, UIAlertActionStyle.default.rawValue] '..... – AnD

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) 

} 

} 
+0

これは私が探していたものです。 – Jan

0

を参照してくださいあなたはこれを試すことができ、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) 

    } 

と私は@William胡によって溶液に基づいて使用しています何の任意のViewController

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

からshowAlertViewメソッドを呼び出します。

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を与えます既定ではにオプションで使用できます。
  2. アレイbuttonTexts,buttonStylesおよびhandlersは、要件ごとに異なるサイズであってもよい。
  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)