ios - 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
}
解决方案
您可以通过 UIApplication 的共享实例访问当前窗口。
if let window = UIApplication.shared.delegate?.window {
window?.rootViewController?.present(alertController, animated: true, completion: nil)
}
推荐阅读
- ios - 如何在sqlite swift中为选定的列设置别名
- java - “应用程序链接”不适用于 android 中的 github 页面
- php - 如果工人在 Gearman 注册,请检查 PHP
- regex - 正则表达式匹配反应样式组件
- django - 使用不在按字段分组的字段排序 django orm
- terraform - vSphere 错误 - 配置的 PCI 设备未连接到 VM
- amazon-web-services - 写 docker 日志 Amazon S3
- zebra-printers - 使用代码配置 Zebra 打印机属性
- react-native - 如何从 React Native 中的数组中依次播放曲目?
- javascript - TypeError:无法读取 react-native 中未定义的属性“样式”