【发布时间】:2018-09-10 11:16:44
【问题描述】:
我知道了
#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
}
我知道 enum 没有 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
}
【问题讨论】:
-
目前已由 k.zoli 解决 - 不幸的是在 viewDidLoad 函数中无法使用
-
在 viewDidLoad 中,我遇到了崩溃,因为还没有视图是列表“Test.ViewController: 0x7fdb21c07bc0> 其视图不在窗口层次结构中!”。视图可见后,视图在层次结构中“然后它可以工作。在 viewDidAppear 中它可以工作。但是我在 viewDidLoad 中进行图像设置。使用最新的 k.zoli 示例,它在 viewDidLoad 中也很有效。
标签: ios macos enums uiimage nsimage