WatchOS Using ObservableObject in Conditional in View Causing Runtime Error
Solution 1:
I was having the same issue for a long time, and this is still happening on Xcode 13.2.1.
Seems to be an issue with TabView
on watchOS, because if you replace the TabView for another View the error is gone.
The solution is to use the initialiser for TabView
with a selection
value: init(selection:content:)
1 Define a property for selection
@State private var selection = 0
2 Update TabView
From
TabView {
// content
}
To
TabView(selection: $selection) {
// content
}
Updating your code would look like this:
struct MultiPageView: View {
@StateObject var subscribed = SubscribedModel()
@State private var selection = 0
var body: some View {
if subscribed.value {
TabView(selection: $selection) {
ViewOne()
ViewTwo()
ViewThree()
ToggleView(subscribed: $subscribed.value)
}
.tabViewStyle(PageTabViewStyle())
} else {
TabView(selection: $selection) {
ViewOne()
ToggleView(subscribed: $subscribed.value)
}
.tabViewStyle(PageTabViewStyle())
}
}
}
Basically just defining a @State
property for TabView.selection
, and using it on both your TabViews (using separated properties would also work).