首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Swift中提取`UIBlurEffect.Style`枚举大小写名称

如何在Swift中提取`UIBlurEffect.Style`枚举大小写名称
EN

Stack Overflow用户
提问于 2021-01-23 01:43:11
回答 1查看 77关注 0票数 0

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

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

我也尝试使用Mirror,但得到的名称是__C.UIBlurEffectStyle

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

代码语言:javascript
复制
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和Xcode12.3

作为参考,Apple对枚举的定义如下:

代码语言:javascript
复制
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

    ...
EN

回答 1

Stack Overflow用户

发布于 2021-01-23 05:43:20

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

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

代码语言:javascript
复制
let blurStyle = String(describing: UIBlurEffect(style: .systemMaterialDark))
let style = blurStyle.components(separatedBy: "style=").last?.replacingOccurrences(of: "UIBlurEffectStyle", with: "")
print(style) // SystemMaterialDark

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

代码语言:javascript
复制
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属性,逐个映射它们:

代码语言:javascript
复制
extension UIBlurEffect.Style {
    var name: String {
        switch self {
            case .extraLight: "extraLight"
            case .dark: "dark"
            case .light: "light"
            case .regular: "regular"
            ...
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65850173

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档