【SwiftUI】タブバーのタップ判定を取得する方法

実装

struct ContentView: View {
    @State var activeTabIndex = 1
    
    var body: some View {
        TabView(selection: $activeTabIndex) {
            Tab1()
                .tabItem {
                    Image(systemName: "square.and.arrow.up")
                    Text("TabA")
                }
                .tag(1)
            Tab2()
                .tabItem {
                    Image(systemName: "pencil.circle")
                    Text("TabB")
                }
                .tag(2)
        }
        .onChange(of: activeTabIndex) { selection in
            switch selection {
            case 1:
                print("TabAがタップされた")
            case 2:
                print("TabBがタップされた")
            default:
                break
            }
        }
    }
}

struct Tab1: View {
    var body: some View {
        Text("HomeView")
    }
}

struct Tab2: View {
    var body: some View {
        Text("NewsListView")
    }
}