英文:
@State variable $ sign usage
问题
Learning SwiftUI and having some difficulty in understanding @State. For example in the code below, why don't we use State variable (that is with $ sign) with if statement? Why only as Toggle argument? How do we differentiate both the states?
学习SwiftUI并且在理解@State时遇到一些困难。例如,在下面的代码中,为什么我们不在if语句中使用State变量(带有$符号)?为什么只在Toggle参数中使用?我们如何区分这两种状态?
英文:
Learning SwiftUI and having some difficulty in understanding @State. For example in the code below, why don't we use State variable (that is with $ sign) with if statement? Why only as Toggle argument? How do we differentiate both the states?
import SwiftUI
struct ContentView: View {
@State private var isFrown = true
var body: some View {
VStack
{
Text ("Check toggle state")
Toggle(isOn: $isFrown) {
Text("")
.padding()
if isFrown { //why not $isFrown here
Text("🤨")
}
else {
Text("😃")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
答案1
得分: 3
@State
是一个属性包装器结构,它只是包装任何值,以确保您的视图在该值更改时刷新或重绘。
(https://developer.apple.com/documentation/swiftui/state)
使用 $
美元符号可以访问状态结构的 projectedValue
,在这种情况下,它提供了一个 Binding
(https://developer.apple.com/documentation/swiftui/binding),最好通过文档解释:
使用绑定来创建视图与其底层模型之间的双向连接。例如,您可以在 Toggle 和 State 的 Bool 属性之间创建一个绑定。与切换控件交互会更改 Bool 的值,而更改 Bool 的值会导致切换更新其呈现的状态。
英文:
@State
is a property wrapper struct that just wraps any value to make sure your view will refresh or redraw whenever that value changes.
(https://developer.apple.com/documentation/swiftui/state)
Using a $ dollar sign provides access to the projectedValue
of the state struct, which in this case gives a Binding
(https://developer.apple.com/documentation/swiftui/binding), best explained by the documentation:
> Use a binding to create a two-way connection between a view and its
> underlying model. For example, you can create a binding between a
> Toggle and a Bool property of a State. Interacting with the toggle
> control changes the value of the Bool, and mutating the value of the
> Bool causes the toggle to update its presented state.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论