2017-03-15 72 views
0

我在另一个类的单独的swift文件中有以下的Swift 3代码。如何显示不是UIViewController的另一个类的警报弹出窗口?

class Login{ 

    func showAlert(message :String){ 

     let alertController2 = UIAlertController(title: "Error", message: "A error occured when checking credentials, try again later.", preferredStyle: .alert) 
     let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) 
     alertController2.addAction(defaultAction) 
     self.present(alertController2, animated: true, completion: nil) 
    } 
} 

但我得到一个红色的错误:

Use of unresolved identifier 'UIAlertController'

如何创建一个弹出窗口,告知出现了错误的用户?

回答

0

首先,你需要:

import UIKit 

但你的更大的问题是,你要使用本()方法的UIViewController对象的方法,并且也只能在其视图视图控制器已经是视图层次结构的一部分。

所以我认为你需要重构你的代码,并决定哪个视图控制器应该启动你的警报。

0
import Foundation 
import UIKit 
class Utility: NSObject{ 

    func showAlert(_ VC : UIViewController, andMessage message: String , handler :@escaping(UIAlertAction) -> Void){ 

    let alert = UIAlertController(title: "Error", message: message , preferredStyle: UIAlertControllerStyle.alert) 
    alert.addAction(UIAlertAction(title: "Ok", style:UIAlertActionStyle.default, handler: handler)) 
    VC.present(alert, animated: true, completion: nil) 

    } 
} 

试试这个,这会奏效。

1

首先,您需要import UIKit才能让UIAlertController显示给您的班级。

这段代码将获得当前的视图控制器,即使它是一个模态。

func topViewController() -> UIViewController? { 
    guard var topViewController = UIApplication.shared.keyWindow?.rootViewController else { return nil } 
    while topViewController.presentedViewController != nil { 
     topViewController = topViewController.presentedViewController! 
    } 
    return topViewController 
} 

所以,你现在可以得到控制,并存在于其上的警告:

topViewController()?.present(alertController2, animated: true, completion: nil)