有没有办法创建一个修改器来更新@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
from .red
如果我需要对该 ChildView 进行更多自定义,则可以更改为其他颜色。我想要实现的目标的示例:
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
关键字来自那个var
并通过color
作为构造函数中的参数(例如:ChildView(theText: "Hello World", color: .green)
),但我不认为这是解决这个问题的方法,因为如果我需要对子视图进行更多自定义,我最终会得到一个非常大的构造函数。
那么,关于如何实现我想要的目标有什么想法吗?希望我能解释一下自己:)
谢谢!!!