SwiftUI状态绑定:@State

官方文档:

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.

原理图

image.png

效果图:

image.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()
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容