Why does SwiftUI's TabView rotation to landscape jump to random tab-number?

Viewed 770

Using Swift 5.3.2, Xcode 12.4, iOS 14.4,

I am trying to make a simple Page-TabView in SwiftUI (see below code-excerpt).

When rotating to Landscape or back to Portrait, there is a problem (see video):

Whenever I rotate my iPhone, the TabView "jumps" to a random tab-number.

Why is this ?

What can I do make the TabView keep the current tab-number when rotating ?

(I am using an iPhoneX)

There seem more issues with the new iOS14 TabView's PageControl function as decribed here. (Maybe the "random tab-number" when rotating the device is related to the layout-issue described)

enter image description here

import SwiftUI

@main
struct MyApp: App {
    
    var body: some Scene {
        WindowGroup {
            TabView {
                Text("1")
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background(Color.pink)
                Text("2")
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background(Color.yellow)
                Text("3")
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background(Color.green)
                Text("4")
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background(Color.blue)
            }
            .tabViewStyle(PageTabViewStyle())
        }
    }
}
1 Answers

One of a solution is to set back to active tab item using custom view modifier for example, this. It seems jump happens after rotation finish, so delayed timer could be used:

// Implement your rotation change modifier
.onChange(of: isLandscape) { _ in
    if selectedTab > 0 { // Do not reset for first element
        let beforeIndex = selectedTab
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
            selectedTab = beforeIndex
        }
    }
}

And the result is:

enter image description here

Full source code here

Related