Cannot Use Tabview on Swiftui, Watchos

SwiftUI Tab Selection Not Working With Any Hashable Content

No, it is not SwiftUI bug. Type of selection and type of tag must be same, so in your first scenario they are both integers, but in second one they are not same - selection is ColorItem, but tag is still integer - thus selection does not work.

Here is fixed variant:

struct TabViewBroken: View {
@State private var tabSelection = ColorItem(color: .red, title: "Red")
let items: [ColorItem]

var body: some View {
ZStack{
TabView(selection: $tabSelection){
ForEach(0..<items.count){ i in
items[i].color.edgesIgnoringSafeArea(.all)
.tag(items[i]) // << here !!
}
}
.tabViewStyle(PageTabViewStyle())

VStack{
Text(items.firstIndex(of: tabSelection)?.description ?? "N/A")
Text(tabSelection.title)
}
.font(.largeTitle)
}
}
}

How can I use navigationBarTitleDisplayMode on watchOS 7 and below?

You can do it with a ViewBuilder extension:

extension View {
@ViewBuilder
func navBarTitleDisplayMode(_ mode: NavigationBarItem.TitleDisplayMode) -> some View {
if #available(watchOSApplicationExtension 8.0, *) {
self
.navigationBarTitleDisplayMode(mode)
} else {
self
}
}
}

Usage:

someView
.navigationBarTitle("WatchFunk") // Using this for watchOS 6 compatibility.
// Use navigationTitle when targeting
// watchOS 7 and above.
.navBarTitleDisplayMode(.inline)

WatchOS Using ObservableObject in Conditional in View Causing Runtime Error

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).



Related Topics



Leave a reply



Submit