class AlbumViewModel: ObservableObject {
@Published var currentAssetLocalIdentifier: String?
}
extension EnvironmentValues {
var albumViewModel: AlbumViewModel {
get {
return self[AlbumViewModelKey.self]
}
set {
self[AlbumViewModelKey.self] = newValue
}
}
}
private struct AlbumViewModelKey: EnvironmentKey {
static let defaultValue: AlbumViewModel = AlbumViewModel()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Environment(\.albumViewModel) var albumViewModel: AlbumViewModel
var body: some View {
...
/// @Environment unlike @StateObject, can not using $albumViewModel.$currentAssetLocalIdentifier.
TabView(selection: .init(get: {
albumViewModel.currentAssetLocalIdentifier
}, set: { id in
albumViewModel.currentAssetLocalIdentifier = id
})) {
....
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18