ios - 如何显示来自另一个不是 UIViewController 的类的警报弹出窗口?

标签 ios swift3 uialertcontroller

我在另一个类的单独 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)
     }
}

但我收到一个红色错误:

Use of unresolved identifier 'UIAlertController'



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

最佳答案

首先你需要import UIKit为了使UIAlertController对您的类(class)可见。

此代码将获取当前 View Controller ,即使它是模态的。

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

因此,您现在可以获得 Controller 并在其上显示警报:
topViewController()?.present(alertController2, animated: true, completion: nil)

关于ios - 如何显示来自另一个不是 UIViewController 的类的警报弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42819859/

相关文章:

iOS 我们可以重用 NSTimer

ios - 点击另一个 UITextField 后自动禁用键盘

ios - 返回在 UIAlertControllerStyle.ActionSheet 中选择的 Action

ios - 如何定位 UIAlertController View ?

ios - mbtiles:是否可以在离线 mbtiles map 上画一些线

ios - 根据SwiftUI中的宽度计算每行的项目数

ios - 在 tableViewCell Swift 上点击手势

ios - Xcode 8 iOS 模拟器没有在我的 Swift 3 项目中提示位置服务授权

ios - UIAlertController 的按钮在单击时更改其颜色。怎么解决? - swift

iphone - Objective C 中的二维数组