有没有办法创建修改器来更新 @State private var
在 View 被修改?
我有一个自定义 View ,它返回 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)
}
}
}
}
我在我的应用程序的不同部分重复使用这个 View 。如您所见,我需要指定的唯一参数是 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
}
}
}
到目前为止没有什么花哨的。现在,我需要的是创建(也许)一个修饰符或类似的东西,以便在父 View 中我可以更改
@State private var color
的值。来自 .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)
),但我认为这不是解决这个问题的方法,因为如果我需要对 subview 进行更多自定义,我最终会得到一个非常大的构造函数。那么,关于如何实现我正在寻找的任何想法?希望我自己解释:)
谢谢!!!
最佳答案
这是您的 View ,修饰符只是生成另一个修改后的 View 的函数,所以......这里有一些可能的简单方法来实现您想要的。
使用 Xcode 12/iOS 14 测试
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)
}
}
}
// simply modify self, as self is just a value
public func someModifierOrTheLike(color: Color) -> some View {
var view = self
view._color = State(initialValue: color)
return view.id(UUID())
}
}
关于用于自定义 View 的 SwiftUI ViewModifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64363228/