在 SwiftUI 中复制 foregroundStyle(_:)

问题描述 投票:0回答:1

在 SwiftUI 中,foregroundStyle(_:) 似乎做了一些 @environment 魔法,但它也无法通过我能找到的任何

@Environment(\.insertMagicKeyHere)
键访问,所以我一直在尝试制作自己的版本来应用一些自定义视图。

但是,在视图中,当我尝试应用自定义视图时,它给了我一个错误:

@Environment(\.elementStyle) var elementStyle

var body: some View {
    CustomShape()
        .foregroundStyle(elementStyle) //Type 'any ShapeStyle' cannot conform to 'ShapeStyle'
}

我相信我明白为什么这是一个问题,但我不知道让我的修改器接受任何类型的魔法酱是什么

ShapeStyle.
我已经尝试了许多不同的泛型或诸如此类的东西,但我只是可以我一生都不知道如何存储符合
ShapeStyle
的对象以用于填充形状。

苹果是如何做到的?难道有什么我不明白的魔法吗?作为参考,下面提供了我的环境密钥。我希望不必为每种 ShapeStyle 编写不同的修饰符/键。一定有一种我没有看到的方法可以做到这一点,对吗?

struct ElementStyleKey: EnvironmentKey {
    static var defaultValue: any ShapeStyle = .primary
}

extension EnvironmentValues {
    var elementStyle: any ShapeStyle {
        get { self[ElementStyleKey.self] }
        set { self[ElementStyleKey.self] = newValue }
    }
}

struct ElementStyleModifier: ViewModifier {
    var style: any ShapeStyle
    func body(content: Content) -> some View {
        content
            .environment(\.elementStyle, style)
    }
}

extension View {
    public func elementStyle(_ style: any ShapeStyle) -> some View {
        modifier(ElementStyleModifier(style: style))
    }
}
swift generics swiftui swift-protocols swiftui-environment
1个回答
0
投票

可能您需要将

any ShapeStyle
更改为
HierarchicalShapeStyle

struct TestView: View {
    @Environment(\.elementStyle) var elementStyle

    var body: some View {
        CustomShape()
            .foregroundStyle(elementStyle)
    }
}

struct ElementStyleKey: EnvironmentKey {
    static var defaultValue: HierarchicalShapeStyle = .primary
}

extension EnvironmentValues {
    var elementStyle: HierarchicalShapeStyle {
        get { self[ElementStyleKey.self] }
        set { self[ElementStyleKey.self] = newValue }
    }
}

struct ElementStyleModifier: ViewModifier {
    var style: HierarchicalShapeStyle
    
    func body(content: Content) -> some View {
        content
            .environment(\.elementStyle, style)
    }
}

extension View {
    public func elementStyle(_ style: HierarchicalShapeStyle) -> some View {
        modifier(ElementStyleModifier(style: style))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.