Change Color Scheme of SwiftUI View not working when it is inside UIHostingController

57 Views Asked by At

All I have a simple SwiftUI View like this:

struct SettingsSUView: View {
  @State private var isPresented = false
  @State private var isDarkMode = true
  var body: some View {
    Button("Show Sheet") {
      isPresented = true
    }
    .sheet(isPresented: $isPresented) {
      List {
        Toggle("Dark Mode", isOn: $isDarkMode)
      }
      .preferredColorScheme(isDarkMode ? .dark : .light)
    }
  }
}

#Preview {
  SettingsSUView()
}

The color scheme changes like normal when it runs in Preview and run as a standalone SwiftUIView, but when it was put in a UIHostingController color scheme stopped changing.

    let contentHostingController = UIHostingController(rootView: SettingsSUIView())
    addChild(contentHostingController)
    view.addSubview(contentHostingController.view)
    
    contentHostingController.view.snp.makeConstraints { make in
      make.edges.equalToSuperview()
    }
    
    contentHostingController.didMove(toParent: self)

I've tried many things like using contentHostingController.overrideUserInterfaceStyle = .dark but most of them can only be changed in 1 way and do not update the SwiftUI view color scheme to match with the changes of the Toggle.

0

There are 0 best solutions below