[英]Changing @State variable does not update the View in SwiftUI
I have a following View (took out irrelevant parts):我有以下观点(去掉不相关的部分):
struct Chart : View {
var xValues: [String]
var yValues: [Double]
@State private var showXValues: Bool = false
var body = some View {
...
if showXValues {
...
} else {
...
}
...
}
}
then I wanted to add a way to modify this value from outside, so I added a function:然后我想添加一种从外部修改这个值的方法,所以我添加了一个函数:
func showXValues(show: Bool) -> Chart {
self.showXValues = show
return self
}
so I build the Chart view from the outside like this:所以我像这样从外部构建图表视图:
Chart(xValues: ["a", "b", "c"], yValues: [1, 2, 3])
.showXValues(true)
but it works as if the value was still false.但它的工作方式就好像该值仍然为假。 What am I doing wrong?
我究竟做错了什么? I thought updating an @State variable should update the view.
我认为更新 @State 变量应该更新视图。 I am pretty new to Swift in general, more so to SwiftUI, am I missing some kind of special technique that should be used here?
总的来说,我对 Swift 很陌生,对 SwiftUI 更是如此,我是否缺少某种应该在这里使用的特殊技术?
As in the comments mentioned, @Binding
is the way to go.正如在提到的评论中,
@Binding
是要走的路。
Here is a minimal example that shows the concept with your code:这是一个最小的示例,显示了您的代码的概念:
struct Chart : View {
var xValues: [String]
var yValues: [Double]
@Binding var showXValues: Bool
var body: some View {
if self.showXValues {
return Text("Showing X Values")
} else {
return Text("Hiding X Values")
}
}
}
struct ContentView: View {
@State var showXValues: Bool = false
var body: some View {
VStack {
Chart(xValues: ["a", "b", "c"], yValues: [1, 2, 3], showXValues: self.$showXValues)
Button(action: {
self.showXValues.toggle()
}, label: {
if self.showXValues {
Text("Hide X Values")
}else {
Text("Show X Values")
}
})
}
}
}
Okay, answer is pretty dumb.好吧,答案很愚蠢。
There is no need to create func
-s.无需创建
func
-s。 All I have to do is not mark the properties as private but give them an initial value, so they're gonna become optional in the constructor.我所要做的不是将属性标记为私有,而是给它们一个初始值,这样它们就会在构造函数中成为可选的。 So user can either specify them, or not care.
所以用户可以指定它们,也可以不关心。 Like this:
像这样:
var showXLabels: Bool = false
This way the constructor is either Chart(xLabels:yLabels)
or Chart(xLabels:yLabels:showXLabels)
.这样构造函数是
Chart(xLabels:yLabels)
或Chart(xLabels:yLabels:showXLabels)
。
Question had nothing to do with @State.问题与@State 无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.