我明白了
#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
}
答案 0 :(得分:0)
您可以通过UIApplication的共享实例访问当前窗口。
if let window = UIApplication.shared.delegate?.window {
window?.rootViewController?.present(alertController, animated: true, completion: nil)
}