2

I'm trying to force a layout direction using .environment(\.layoutDirection, .rightToLeft) modifier on a View.

I'm using the following hierarchy:

let layoutDirection = LayoutDirection.rightToLeft
let view = SettingsView().environment(\.layoutDirection, layoutDirection)

let settingsViewController = UIHostingController(rootView: view)
let navigationController = UINavigationController(rootViewController: settingsViewController)

present(navigationController, animated: true)

SettingsView has a NavigationLink to submenu items.

LayoutDirection is only set to right on the root view (SettingsView) and is ignored in child views.

I tried putting .environment(\.layoutDirection, .rightToLeft) not just after root initializer but also on List and Section items in root view. They are all ignored except when setting them specifically to various submenu initializers.

I tried the same thing in a pure SwiftUI app and passing the environment value to children works as expected. Could UIHostingController or UINavigationController be the issue here?

Additionally, I tried the same thing with a custom environment value. Example from https://developer.apple.com/documentation/swiftui/environmentvalues . It also doesn't get passed to child views.

1 Answers1

0

You should state the child view relation in order to have the HostingController work as expected. Please have a look at the documentation:

https://developer.apple.com/documentation/swiftui/uihostingcontroller

You can check an example here:

https://medium.com/@max.codes/use-swiftui-in-uikit-view-controllers-with-uihostingcontroller-8fe68dfc523b

Matias Contreras
  • 442
  • 5
  • 10
  • Hmm, I'm trying to do the same thing as the medium article suggests, my child views are still not receiving the environment property. I'm also looking at the documentation and I'm not sure what I'm doing wrong. – Lukas Šestić Nov 03 '22 at 07:30
  • Could you try passing the layoutDirection in the init as a param? Does it work with the preview? – Matias Contreras Nov 03 '22 at 12:08
  • Yes, we could do that but we want to avoid doing something that is supposed to work "out of the box". The preview works as it's "pure SwiftUI", UIHosting breaks the thing I guess. Thanks for your help though! :) – Lukas Šestić Nov 03 '22 at 12:53