2017-03-15 71 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)