Post

SwiftUI4:Binding

参考:

使用Binding属性可以对属性的变化进行监听及相关业务逻辑处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// 不使用binding
struct ContentView1: View {
    @State var selection = 0

    var body: some View {
        return VStack {
            Picker("Select a number", selection: $selection) {
                ForEach(0 ..< 3) {
                    Text("Item \($0)")
                }
            }.pickerStyle(SegmentedPickerStyle())
            Text("selected: \(selection)")
        }
    }
}
// 使用binding拦截get/set
struct ContentView2: View {
    @State var selection = 0

    var body: some View {
        let binding = Binding(
            get: { self.selection },
            set: { self.selection = $0 }
        )

        return VStack {
            Picker("Select a number", selection: binding) {
                ForEach(0 ..< 3) {
                    Text("Item \($0)")
                }
            }.pickerStyle(SegmentedPickerStyle())
            Text("selected: \(selection)")
        }
    }
}
// 使用binding做复杂的组合业务逻辑
struct ContentView3: View {
    @State var agreedToTerms = false
    @State var agreedToPrivacyPolicy = false
    @State var agreedToEmails = false

    var body: some View {
        let agreedToAll = Binding<Bool>(
            get: {
                self.agreedToTerms && self.agreedToPrivacyPolicy && self.agreedToEmails
            },
            set: {
                self.agreedToTerms = $0
                self.agreedToPrivacyPolicy = $0
                self.agreedToEmails = $0
            }
        )

        return VStack {
            Toggle(isOn: $agreedToTerms) {
                Text("Agree to terms")
            }

            Toggle(isOn: $agreedToPrivacyPolicy) {
                Text("Agree to privacy policy")
            }

            Toggle(isOn: $agreedToEmails) {
                Text("Agree to receive shipping emails")
            }

            Toggle(isOn: agreedToAll) {
                Text("Agree to all")
            }
            Text("terms: \(agreedToTerms ? "true" : "false")")
            Text("policy: \(agreedToPrivacyPolicy ? "true" : "false")")
            Text("emails: \(agreedToEmails ? "true" : "false")")
            Text("all: \(agreedToAll.wrappedValue ? "true" : "false")")
        }
    }
}

// 调用demo
#Preview {
    VStack(spacing: 10) {
        ContentView1()
        ContentView2()
        ContentView3()
    }
}

image

This post is licensed under CC BY 4.0 by the author.