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

60 views Asked by At

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?

1

There are 1 answers

1
LucasC On BEST ANSWER

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()
}