【问题标题】:How to extract name of enum case of `UIBlurEffect.Style` in Swift如何在 Swift 中提取“UIBlurEffect.Style”的枚举大小写名称
【发布时间】:2021-01-22 17:43:11
【问题描述】:

我正在尝试以编程方式提取 UIBlurEffect.Style 的枚举案例的名称,其中 rawValueInt 而不是 String。数组中的名称为["extraLight","light","dark","regular",...]

执行print(UIBlurEffect.Style.systemChromeMaterialLight) 不会打印systemChromeMaterialLight,而是打印UIBlurEffectStyle

我也尝试使用Mirror,但这会产生__C.UIBlurEffectStyle的名称

我正在尝试做的示例代码:

let myStyles : [UIBlurEffect.Style] = [.light, .dark, .regular, .prominent]
for style in myStyles {
  print(style) // does not work, produces "UIBlurEffectStyle"
  myFunction(styleName: String(reflecting: style)) // does not work, produces "UIBlurEffectStyle"
  myFunction(styleName: String(describing: style)) // does not work, produces "UIBlurEffectStyle"
  myFunction(styleName: "\(style)") // does not work, produces "UIBlurEffectStyle"
}

我正在使用 Swift 5、iOS 14 和 Xcode 12.3

供参考,枚举由Apple定义如下:

extension UIBlurEffect {
    @available(iOS 8.0, *)
    public enum Style : Int {
        case extraLight = 0
        case light = 1
        case dark = 2
        
        @available(iOS 10.0, *)
        case regular = 4

    ...

【问题讨论】:

  • @impression7vx 不起作用
  • 可能必须为每个案例制作一个switch 声明,然后您可以简单地调用描述。 stackoverflow.com/a/52077091/5009432

标签: swift enums


【解决方案1】:

您是否正在做一些与应用名称相关的动态操作,以便根据选择显示正确的名称? 如果你是,我建议你创建自己的本地 String 枚举,然后添加一个 var 或函数来从中获取模糊,而不是试图反转它。

但如果你真的、真的因为其他原因需要这个,有一个解决方法,我不推荐,但如果你想测试一下,它就在这里:

let blurStyle = String(describing: UIBlurEffect(style: .systemMaterialDark))
let style = blurStyle.components(separatedBy: "style=").last?.replacingOccurrences(of: "UIBlurEffectStyle", with: "")
print(style) // SystemMaterialDark

创建您自己的应用样式枚举:

enum AppBlurStyle: String {
    case extraLight
    case dark
    case light
    case regular
    
    var blurEffectStyle: UIBlurEffect.Style {
        switch self {
            case .extraLight: UIBlurEffect.Style.extraLight
            case .dark: UIBlurEffect.Style.dark
            case .light: UIBlurEffect.Style.light
            case .regular: UIBlurEffect.Style.regular
        }
    }
    
    var blurEffect: UIBlurEffect {
        switch self {
            case .extraLight: UIBlurEffect(style: .extraLight)
            case .dark: UIBlurEffect(style:.dark)
            case .light: UIBlurEffect(style:.light)
            case .regular: UIBlurEffect(style:.regular)
        }
    }
}

或者你甚至可以扩展 UIBlurEffect.Style 并添加一个 name 属性,分别映射它们:

extension UIBlurEffect.Style {
    var name: String {
        switch self {
            case .extraLight: "extraLight"
            case .dark: "dark"
            case .light: "light"
            case .regular: "regular"
            ...
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多