Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

ios - TabView (SwiftUI): Respond onTab on an already active tabItem

I have a ContentView.swift which contains a TabView.

View1 has a NavigationView in it with some childViews. View2 is just a single View.

I would like to perform some action (always return to View1, even when being in a childView of View1), when the first tabItem is pressed. Even if it is already the active tabItem.

I tried onTapGesture as seen below, which didn't seem to do anything. Adding it right before ".tag(0)" didn't change anything, either:

                            TabView {
                            View1()
                                .onTapGesture {
                                    print("Test")
                            }
                                .tabItem {
                                    Image(systemName: "doc.plaintext")
                                        .font(.system(size: 25))
                                    Text("View1")
                            }.tag(0)

                            View2()
                                .tabItem {
                                    Image(systemName: "person.crop.circle")
                                        .font(.system(size: 25))
                                    Text("View2")
                            }.tag(1)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is possible approach. Tested with Xcode 11.4 / iOS 13.4

struct TestTabSelectionAction: View {
    @State private var selectedTab = 0

    var body: some View {
        let selection = Binding<Int>(
            get: { self.selectedTab },
            set: { self.selectedTab = $0
                print("Pressed tab: ($0)")
                if $0 == 0 {
                           // <<< your action here !!
                }
        })

        return TabView(selection: selection) {
            View1()
            .tabItem {
                Image(systemName: "doc.plaintext")
                    .font(.system(size: 25))
                Text("View1")
            }.tag(0)

            View2()
                .tabItem {
                    Image(systemName: "person.crop.circle")
                        .font(.system(size: 25))
                    Text("View2")
            }.tag(1)
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...