Force RTL or LTR in SwiftUI Force RTL or LTR in SwiftUI swift swift

Force RTL or LTR in SwiftUI


You may one to make the app default language to some Right To Left like Persian in info.plist or with other methods:

Info.plist


If you need to force a view, Just apply this modifier on any view you like:

.environment(\.layoutDirection, .rightToLeft)

You can apply to the ContentView() in SceneDelegate to make it available for all subviews.


You can either set layout direction in the Scene Delegate:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {        let contentView = ContentView().environment(\.layoutDirection, .rightToLeft)        if let windowScene = scene as? UIWindowScene {            let window = UIWindow(windowScene: windowScene)            window.rootViewController = UIHostingController(rootView: contentView)            self.window = window            window.makeKeyAndVisible()        }    }

or manually disable change of direction on some views using this modifier:

.flipsForRightToLeftLayoutDirection(true)


I tried everything to force SwiftUI to be RTL Arabic, Like...

import SwiftUI    @main    struct MyApp: App {        init() {            UserDefaults.standard.set(["ar"], forKey: "AppleLanguages")        }                var body: some Scene {            WindowGroup {                             ContentView()                    .environment(\.locale, Locale(identifier: "ar"))                    .environment(\.layoutDirection, .rightToLeft)            }        }    }

But this way cause a lot of bugs if you use NavigationViewThe best solution is...

import SwiftUI    @main    struct MyApp: App {        init() {            UserDefaults.standard.set(["ar"], forKey: "AppleLanguages")        }                var body: some Scene {            WindowGroup {                             ContentView()            }        }    }