#StackBounty: #swiftui SwiftUI Tabbar persists navigationBarTitle position in tab's views

Bounty: 500

How can I stop this from happening? I don’t necessarily want to force the scroll view to the top every time you show a new tab, but just want the new tabs to be affected by the last.

import SwiftUI

enum Tab {
    case First, Second, Third
    
    var title: String {
        switch self {
        case .First:
            return "First"
        case .Second:
            return "Second"
        case .Third:
            return "Third"
        }
    }
}

struct ContentView: View {
    @State var selectedTab = Tab.First
    var body: some View {
        NavigationView {
            TabView(selection: $selectedTab) {
                FirstView()
                    .tabItem {
                        Text("First")
                    }.tag(Tab.First)
                SecondView()
                    .tabItem {
                        Text("Second")
                    }.tag(Tab.Second)
                ThirdView()
                    .tabItem {
                        Text("Third")
                    }.tag(Tab.Third)
            }.navigationBarTitle(selectedTab.title, displayMode: .automatic)
            .navigationBarHidden(false)
        }
    }
}

struct FirstView: View {
    let data = [1,2,3,4,5,6,7,8,9,10]
    var body: some View {
        ScrollView(showsIndicators: true) {
            VStack {
                ForEach(data, id: .self) { item in
                    Text("(item)")
                        .frame(minWidth: 0, idealWidth: 100, maxWidth: .infinity, minHeight: 0, idealHeight: 100, maxHeight: .infinity, alignment: .center)
                }
            }
        }
    }
}

struct SecondView: View {
    let data = [1,2,3,4,5,6,7,8,9,10]
    var body: some View {
        ScrollView(showsIndicators: true) {
            VStack {
                ForEach(data, id: .self) { item in
                    Text("(item)")
                        .frame(minWidth: 0, idealWidth: 100, maxWidth: .infinity, minHeight: 0, idealHeight: 100, maxHeight: .infinity, alignment: .center)
                }
            }
        }
    }
}

struct ThirdView: View {
    let data = [1,2,3,4,5,6,7,8,9,10]
    var body: some View {
        ScrollView(showsIndicators: true) {
            VStack {
                ForEach(data, id: .self) { item in
                    Text("(item)")
                        .frame(minWidth: 0, idealWidth: 100, maxWidth: .infinity, minHeight: 0, idealHeight: 100, maxHeight: .infinity, alignment: .center)
                }
            }
        }
    }
}

enter image description here


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.