Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SwifUI中的@State和@Binding #196

Open
vislee opened this issue Dec 28, 2023 · 0 comments
Open

SwifUI中的@State和@Binding #196

vislee opened this issue Dec 28, 2023 · 0 comments

Comments

@vislee
Copy link
Owner

vislee commented Dec 28, 2023

@State 是swiftUI的一个属性装饰器,可以将被修饰的属性改为有状态的,当其发生改变时,与其绑定的组件会自动更新。
@binding 同样是个属性装饰器,修饰子组件的属性,绑定父State的属性。

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.cyan)
            Text("Hello, world!")
        }
        .padding()
    }
}


struct RowContent: View {
    @Binding var count:Int
    var body: some View {
        VStack {
            Button(action: {count += 1}) {
                Text("点我")
            }
            Text("click count: \(count)")
            
        }
    }
}


struct MainVeiw: View {
    @State var count:Int = 0
    var body: some View {
        NavigationView {
            List {
                NavigationLink("aaa") {
                    ContentView()
                }
                NavigationLink("bbb") {
                    RowContent(count: $count)
                }
            }
        }
        .navigationTitle("通讯录")
    }
}

#Preview {
    MainVeiw()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant