假设我有一个绑定的字符串:
@Binding var string: String
但是,我想处理该字符串,然后将其传递给子视图.
struct ViewOne: View {
@State var string: String = "Hello"
var body: some View {
ViewTwo(string: string + " World") // this is invalid, as ViewTwo requires Binding<String>
}
}
struct ViewTwo: View {
@Binding var string: String
var body: some View {
Text(string)
}
}
我应该如何操作该字符串,使其在状态更改时更新UI?假设我想为不同的组件重用ViewTwo
,因此我想在将字符串传递到视图之前对其进行操作.
计算变量不起作用,因为它不是Binding
private var fixedString: String {
return string + " World"
}
我不想创建绑定变量,因为setter
在这种情况下没有意义
private var fixedString: Binding<String> {
Binding<String> (
get: {
string + " World"
}, set: {
// this function doesn't make sense here - how would it update the original variable?
}
)
}
我只是用@State
和@Binding
错了吗?