您不应该使用tag
来标识视图.tag
是很难读懂的.它的视图特征键是一个内部类型,因此您需要使用Mirror
.
您可以使用环境来代替.为您将拥有的7+参数中的每一个创建一个环境密钥.
在本例中,有2种 colored颜色 ,因此我将创建2个关键点.如果有更多的 colored颜色 ,我会使用一个数组作为值的键.
struct Color1Key: EnvironmentKey {
static var defaultValue = AnyShapeStyle(.primary)
}
struct Color2Key: EnvironmentKey {
static var defaultValue = AnyShapeStyle(.secondary)
}
extension EnvironmentValues {
var color1: AnyShapeStyle {
get { self[Color1Key.self] }
set { self[Color1Key.self] = newValue }
}
var color2: AnyShapeStyle {
get { self[Color2Key.self] }
set { self[Color2Key.self] = newValue }
}
}
编写您自己的从环境读取的视图修饰符,而不是tag
个.
struct Color1Modifier: ViewModifier {
@Environment(\.color1) var color1
func body(content: Content) -> some View {
content.foregroundStyle(color1)
}
}
struct Color2Modifier: ViewModifier {
@Environment(\.color2) var color2
func body(content: Content) -> some View {
content.foregroundStyle(color2)
}
}
extension View {
func color1() -> some View {
modifier(Color1Modifier())
}
func color2() -> some View {
modifier(Color2Modifier())
}
}
// usage:
VStack {
Text(text1).color1()
Text(text2).color2()
}
.modifier(Watermark(style: ...))
然后,Watermark
可以向环境写入:
func body(content: Content) -> some View {
content
.environment(\.color1, AnyShapeStyle(style == .one ? .red : .black))
.environment(\.color2, AnyShapeStyle(style == .one ? .blue : .pink))
}
以下是相同概念的实现,但使用一个环境键保存一组 colored颜色 :
struct CustomView: View {
var text1: String
var text2: String
public var body: some View {
VStack {
Text(text1).color(0)
Text(text2).color(1)
}
.modifier(Watermark(style: ...))
}
}
struct ColorsModifier: ViewModifier {
let index: Int
@Environment(\.colors) var colors
func body(content: Content) -> some View {
content.foregroundStyle(
colors.indices.contains(index) ? colors[index] : AnyShapeStyle(.opacity(1))
)
}
}
extension View {
func color(_ n: Int) -> some View {
modifier(ColorsModifier(index: n))
}
}
struct ColorsKey: EnvironmentKey {
static var defaultValue: [AnyShapeStyle] = []
}
extension EnvironmentValues {
var colors: [AnyShapeStyle] {
get { self[ColorsKey.self] }
set { self[ColorsKey.self] = newValue }
}
}
struct Watermark: ViewModifier {
enum Style {
case one, two
}
var style: Style
func body(content: Content) -> some View {
content
.environment(
\.colors,
style == .one ?
[.init(.red), .init(.blue)] :
[.init(.black), .init(.pink)]
)
}
}