首页 > 解决方案 > Swift 4.2 - 如何在枚举函数中使用警报?

问题描述

我懂了

#if os(iOS)
import UIKit
import Foundation
#elseif os(OSX)
import Foundation
import cocoa
#else
// Future concerns
#endif


enum Image: String {
    case Preferences
    ....
    case App
    case Stop
    ....
    case Default


    #if os(iOS)
    func image(selected: Bool = false) -> UIImage? {
        let imgName : String = selected ? self.rawValue + "-selected" : self.rawValue
        if let img = UIImage(named:imgName) {
            return img
        } else {
            print("iOS")
            print("Please add the \(imgName) icon to the app assets!!")
            //Creating the alert
            let alertController = UIAlertController(title: "Icon Missing", message: "Please add the \(imgName) image to the app assets!!", preferredStyle: .alert)
            let action = UIAlertAction(title: "I Promiss I will", style: .default, handler: nil)
        alertController.addAction(action)
        // How to get the alert working
     self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
       //
            return nil
        }
    }
    #elseif os(OSX)
    func image(selected: Bool = false) -> NSImage? {
        ....
    }
    #else
    //
    #endif
}

我知道枚举没有 self.window,我只需输入这一行 (self.window?.rootViewController?...) 即可显示问题。有没有让警报工作?当然我不想向 Image.Question.image() 提交视图对象。此外,是否会在开发的后期阶段使用它还有待商榷,但仍然想知道是否有办法。

先感谢您。

========解决=========

借助 k.zoli 的信息和评论,我的主要问题确实得到了解决。

结果代码

func image(selected: Bool = false) -> UIImage? {
        let imgName : String = selected ? self.rawValue + "-selected" : self.rawValue
        guard let img = UIImage(named: imgName) else {
            print("iOS")
            print("Please add the \(imgName) icon to the app assets!!")
            //Creating the alert
            let alertController = UIAlertController(title: "Icon Missing", message: "Please add the \(imgName) icon to the app assets!!", preferredStyle: .alert)
            let action = UIAlertAction(title: "I Promiss I will", style: .default, handler: nil)
            alertController.addAction(action)
            if let window = UIApplication.shared.delegate?.window { DispatchQueue.main.async { window?.rootViewController?.present(alertController, animated: true, completion: nil) } }
            return nil
        }
        return img
    }

标签: iosmacosenumsuiimagensimage

解决方案


您可以通过 UIApplication 的共享实例访问当前窗口。

if let window = UIApplication.shared.delegate?.window {
        window?.rootViewController?.present(alertController, animated: true, completion: nil)
    }

推荐阅读