Home > database >  SwiftUI TabView with PageTabViewStyle in Landscape on device with safeArea adding odd leading edge i
SwiftUI TabView with PageTabViewStyle in Landscape on device with safeArea adding odd leading edge i

Time:10-14

I have a TabView with PageTabViewStyle and when my device is in landscape orientation, there is an odd inset on the leading edge. This is not there on devices without a safeArea and it is not there on any edge in portrait.

struct ContentView: View {

    var body: some View {
        TabView {
            Color.red
                .edgesIgnoringSafeArea(.all)
        }
        .tabViewStyle(PageTabViewStyle())
        .edgesIgnoringSafeArea(.all)
    }
}

enter image description here

CodePudding user response:

That would be the TabView doing that. That is actually the "prior" view, which would be an empty view for your set up. You can see if you run this code in landscape:

var body: some View {
    TabView {
        Color.red
            .edgesIgnoringSafeArea(.all)
        Color.green
            .edgesIgnoringSafeArea(.all)
        Color.blue
            .edgesIgnoringSafeArea(.all)
    }
    .tabViewStyle(PageTabViewStyle())
    .edgesIgnoringSafeArea(.all)
}

Then swipe to the next view. You will see that slice of the screen has turned red. Swipe again and it turns blue.

The fix: set a .frame on the TabView that is the device size, but all of it in a ScrollView and put an .edgesIgnoringSafeArea(.all) on that:

var body: some View {
    ScrollView {
        TabView {
            Color.red
            Color.green
            Color.blue
        }
        .frame(
            width: UIScreen.main.bounds.width ,
            height: UIScreen.main.bounds.height
        )
        .tabViewStyle(PageTabViewStyle())
    }
    .edgesIgnoringSafeArea(.all)
}

And yes, the TabView can scroll vertically, but it will spring back.

  • Related