Search code examples
swiftswiftuitabviewtabitem

How do you vertically center a SwiftUI tabItem


I have created a TabView using SwiftUI. I am trying to have the TabItems in the TabBar centered vertically. However they do not center properly.

import SwiftUI

struct ContentView: View {
    var body: some View {
        TabView(selection: .constant(0)) {
            RouteList()
                .tabItem {
                    Image("subway-3")
                    Text("Trains")
                }.tag(0)

            VStack {
                Text("Tab 2")
            }
            .tabItem {
                Image("subway-3")
                Text("Lines")
            }.tag(1)

            VStack {
                Text("Tab 3")
            }
            .tabItem {
                Image(systemName: "star")
                Text("Slow Zones")
            }.tag(2)
        }
    }
}

Here you can see the result of this code.

TabBar Item Not Centering


Solution

  • You won't be able to centre your tab bar items vertically as they would end up outside the safe area. The empty space at the bottom is the area between the bottom edge of the save area and the bottom edge of the screen. You can compare the look on newer iPhones with a notch to how it draws on older ones where save area extends all the way to the edge of the screen:

    struct ContentView_Previews: PreviewProvider {
    
        static var previews: some View {
            Group {
                ContentView()
                    .previewDevice(PreviewDevice(stringLiteral: "iPhone 8"))
                ContentView()
                    .previewDevice(PreviewDevice(stringLiteral: "iPhone XR"))
            }
        }
    }