SwiftUI @Published 与 onReceive 组合使用

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
import SwiftUI

struct ContentView: View {
@StateObject private var state: ContentViewState = .init()
var body: some View {
VStack {
Text(state.count.description)
Button("Count Up") { state.countUp() }
Button("Reset") { state.reset() }
}
.onReceive(state.$count) { count in
print(count)
}
}
}

final class ContentViewState: ObservableObject {
@Published private(set) var count: Int = 0

func countUp() {
count += 1
}

func reset() {
count = 0
}
}

SwiftUI @Published 与 onReceive 组合使用
https://wonderhoi.com/2024/12/09/SwiftUI-Published-与-onReceive-组合使用/
作者
wonderhoi
发布于
2024年12月9日
许可协议