A very basic example - same behavior...
'[SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.'
import SwiftUI
//MARK: Content View
struct ContentView: View {
@StateObject
private var someVM: SomeViewModel = .shared
var body: some View {
VStack {
if let value = someVM.bindingValue {
HStack {
Text("value:".capitalized)
Text(value.description)
}
.font(.largeTitle)
}
Button {
someVM.isPresented.toggle()
} label: {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundColor(.orange)
Text("Hello, Beta 5 !")
}
.font(.title2)
.buttonStyle(.bordered)
}
.padding()
.sheet(isPresented: $someVM.isPresented) {
SheetView(someVM: .shared)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
//MARK: Sheet View
struct SheetView: View {
@ObservedObject
var someVM: SomeViewModel
var body: some View {
NavigationStack {
List {
ForEach(0..<10) { value in
Button {
someVM.updateValue(for: value)
} label: {
HStack {
Text("value".capitalized)
Spacer()
Text(value.description)
.bold()
.foregroundColor(.red)
}
}
}
}
.navigationTitle("Sheet View")
}
}
}
//MARK: View Model
final class SomeViewModel: ObservableObject {
static let shared: SomeViewModel = .init()
@Published
private (set) var bindingValue: Int? = nil
@Published
var isPresented: Bool = false
func updateValue(for value: Int) {
Task { @MainActor in
bindingValue = value
isPresented.toggle()
}
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: