Search code examples
swiftuiios14xcode12tabviewtabitem

SwiftUI TabView More tab crashes first press


var body: some View {
        TabView {

            ScheduleView().tabItem {
                Image(systemName: "calendar")
                Text("Schedule")
            }.tag(tbScheduleTag)
            DutyBookView().tabItem {
                Image(systemName: "books.vertical")
                Text(dutyBookViewTabText)
            }.tag(tbDutyBookTag)
            TimetableView().tabItem {
                Image(systemName: "calendar.badge.clock")
                Text("Timetable")
            }.tag(tbTimetableTag)
            **... plus 7 other Tabs removed for post readability** 
         }
    }

My TabView creates 10 Tabs so I automatically get the "More" TabItem. After App launches and I press that More tab before anything else the Tab crashes back to the Initial tab. If I tap any other tab first or the More tab again it loads fine. See attached for demo. The first time selected it crashes back the second time it works.

Anyone suggestions please?

enter image description here


Solution

  • I added @State variable and set it to selection attribute of TabView. To make this work I replaced your tags with new enum values.

    struct ContentView: View {
        enum Tab {
            case schedule, dutyBook, timetable, locateTrain, settings
            case tfLRestricted, subscription, serviceStatus, info, storedDuties
        }
        
        @State var tab: Tab = .schedule
        
        var body: some View {
            TabView(selection: self.$tab) { //this is the solution
                ScheduleView().tabItem {
                    Image(systemName: "calendar")
                    Text("Schedule")
                }.tag(Tab.schedule)
                
                DutyBookView().tabItem {
                    Image(systemName: "books.vertical")
                    Text(dutyBookViewTabText)
                }.tag(Tab.dutyBook)
                
                // ...
            }
        }
    }