在 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))
}
}
可能您需要将
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))
}
}