Search code examples
swiftuioverlaytabbartabview

SwiftUI - Overlay TabView with Custom View


I'm having an app with a tab bar navigation concept. For one view I'm currently trying to implement a tab bar overlay that you all know from the Photos App in iOS. It appears when you select images. See below:

Tab Bar Overlay

I tried to implement this behavior in the below code snippet but I have two doubts:

  • is .overlay() the right way to do it? I wanted to combine it with a State and set it accordingly to enable / disable the overlay.
  • if overlay is ok from a coding point of view, how would I align it to the bottom and take care of the sizing so that it exactly overlays the tab bar?
struct ContentView: View {
    var body: some View {
        TabView {
            
            NavigationView {
                Text("First Nav Page")
            }
            .tabItem {
                Image(systemName: "house")
                Text("Home")
                
            }.tag(0)
            
            NavigationView {
                Text("Second Nav Page")
            }
            .tabItem {
                Image(systemName: "gear")
                Text("Settings")
            }.tag(1)
            
            Text("No Nav Page")
                .tabItem{
                    Image(systemName: "plus")
                    Text("Test")
                }.tag(2)
            
        }.overlay(
            Rectangle()
                .foregroundColor(.red)
                .frame(width: 40, height: 40)
        )
    }
}

Thanks!


Solution

  • What you are looking for is a Toolbar, not TabBar. So when the user changes in EditMode, you will have to change the TabBar into the Toolbar.

    The Toolbar is available in iOS 14 and takes a ToolbarItem for the Status in the center and a leading Item with your Icon. You should have to build a function which swapes your TabBar with the Toolbar.

    Here is a example of the Toolbar for your case:

    struct ContentView: View {
        @State var isSelecting : Bool = false
        
        var body: some View {
            NavigationView {
                Text("Hello World")
                    .toolbar {
                        ToolbarItem(placement: .bottomBar, content: {
                                Button(action: {
                                    
                                }){
                                    Image(systemName: "square.and.arrow.up")
                                }
                            })
                    }
                    .toolbar {
                        ToolbarItem(placement: .status, content: {
                                Text("Auswählen")
                                    .fontWeight(.bold)
                        })
                }
            }
        }
    }