SwiftUI状态绑定:@State
2019-11-20 本文已影响0人
mapg
官方文档:
A persistent value of a given type, through which a view reads and monitors the value.SwiftUI manages the storage of any property you declare as a state. When the state value changes, the view invalidates its appearance and recomputes the body. Use the state as the single source of truth for a given view.
原理图
![](https://img.haomeiwen.com/i2045565/f5d25d1b34870d8c.png)
效果图:
![](https://img.haomeiwen.com/i2045565/0e37de904b648d82.png)
相关代码
import SwiftUI
struct ContentView: View{
//加了@State注解的变量,视图通过监视和读取该变量来重新渲染UI。
//其状态是由SwiftUI来存储管理的,作为视图渲染的单一可信来源。
@State private var changgeState:Bool = false
@State private var num:Int = 0;
struct ContentView: View{
//加了@State注解的变量,视图通过监视和读取该变量来重新渲染UI。
//其状态是由SwiftUI来存储管理的,作为视图渲染的单一可信来源。
@State private var changgeState:Bool = false
@State private var num:Int = 0;
var body: some View{
// Text("hello World")
//垂直布局
VStack(alignment: .center, spacing: 5, content:{
Button(action: {
//引用@State的变量时需要加上self的前缀才能正常找到变量
self.changgeState.toggle()
}){
Text("惦记我改变计数显示位置背景")
}
//添加一个$前缀,就可以将State转为Binding。
Stepper("计数器", value:$num).padding(50)
//Z轴布局
ZStack(content: {
Text("显示数值").blur(radius: self.changgeState ? 10 : 0)
Text("\(self.num)")
})
})
}
}
struct ContentView_Previews: PreviewProvider{
static var previews: some View{
ContentView()
}
}