Search code examples
swiftuisidebarsize-classesswiftui-tabview

app loses state when going to background when using sizeClassic in SwiftUI


I have a view created for the iPad with a Sidebar and another for the iPhone with a tabview. The problem is that when I use sizeClass, the SideBarView() view loses its state every time the app enters the background.

This does not happen if I use the SideBarView() view without the sizeClass conditional. Without that variable, it works correctly without any problem.

var body: some View {
    #if os(iOS)
    if horizontalSizeClass == .compact {
        TabMainView()
    } else {
        SideBarView()
    }
    #else //MacOSView
        SideBarView()
    #endif
}

Any idea?


Solution

  • I have changed sizeClass to UIDevice to detect the device and show the corresponding view based on that. This has made the SideBar view work correctly without losing the state at any time.

    Full code:

    extension UIDevice {
    static var idiom: UIUserInterfaceIdiom {
        UIDevice.current.userInterfaceIdiom
      }
    
    static var isIpad: Bool {
        idiom == .pad
      }
    
      static var isiPhone: Bool {
        idiom == .phone
      }
     }
    
    
    if UIDevice.isiPhone {
       TabMainView()
    } else {
       SideBarView()
    }