有没有办法创建一个修饰符来更新在被修改的视图中的
我有一个自定义视图,可以返回带有“动态”背景颜色的
我知道我可以从那个变量中删除"private"关键字并在构造函数中作为参数传递"color"(例如:
所以,你有什么想法可以实现我想要的效果吗?希望我解释清楚了 :) 谢谢!!!
@State private var
?我有一个自定义视图,可以返回带有“动态”背景颜色的
Text
或者带有“动态”前景颜色的Circle
。struct ChildView: View {
var theText = ""
@State private var color = Color(.purple)
var body: some View {
HStack {
if theText.isEmpty { // If there's no theText, a Circle is created
Circle()
.foregroundColor(color)
.frame(width: 100, height: 100)
} else { // If theText is provided, a Text is created
Text(theText)
.padding()
.background(RoundedRectangle(cornerRadius: 25.0)
.foregroundColor(color))
.foregroundColor(.white)
}
}
}
}
我在应用的不同部分中重复使用这个视图。如您所见,我需要指定的唯一参数是theText
。因此,创建此ChildView的可能方式如下:
struct SomeParentView: View {
var body: some View {
VStack(spacing: 20) {
ChildView() // <- Will create a circle
ChildView(theText: "Hello world!") // <- Will create a text with background
}
}
}
到目前为止都很简单。现在,我需要创建一个修改器或类似的东西,以便在父视图中,如果我需要更多定制化,我可以将@State private var color
的值从.red
更改为其他颜色。下面是我试图实现的示例:
struct SomeOtherParentView: View {
var body: some View {
HStack(spacing: 20) {
ChildView()
ChildView(theText: "Hello world!")
.someModifierOrTheLike(color: Color.green) // <- what I think I need
}
}
}
我知道我可以从那个变量中删除"private"关键字并在构造函数中作为参数传递"color"(例如:
ChildView(theText: "Hello World", color: .green)
),但我认为这不是解决这个问题的方法,因为如果我需要更多的子视图自定义,我最终会得到一个非常大的构造函数。所以,你有什么想法可以实现我想要的效果吗?希望我解释清楚了 :) 谢谢!!!