【问题标题】:How do I display an alert popup from another Class that is not a UIViewController?如何显示来自另一个不是 UIViewController 的类的警报弹出窗口?
【发布时间】:2017-03-15 20:17:28
【问题描述】:

我在另一个类的单独 swift 文件中有以下 Swift 3 代码。

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

但我得到一个红色错误:

使用未解析的标识符“UIAlertController”

如何创建一个弹出窗口,通知用户出现问题?

【问题讨论】:

    标签: ios swift3 uialertcontroller


    【解决方案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)
    

    【讨论】:

      【解决方案2】:

      首先,你需要:

      import UIKit
      

      但是您更大的问题是您尝试使用的 present() 方法是 UIViewController 对象的方法,而且它仅适用于视图已经是视图层次结构一部分的视图控制器。

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

      【讨论】:

        【解决方案3】:
        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)
        
           }
        }
        

        试试这个,这会奏效。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-01-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-31
          • 1970-01-01
          • 2013-08-27
          相关资源
          最近更新 更多