SinaMN75
SinaMN75

Reputation: 7659

Force RTL or LTR in SwiftUI

I know SwiftUI changes the direction of the application, based on the system language of the device. but is there a way to ignore the system language and force the app to be always RTL or LTR?

Upvotes: 22

Views: 10906

Answers (3)

iTarek
iTarek

Reputation: 776

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 NavigationView The best solution is...

import SwiftUI

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

Upvotes: 5

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119878

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.

Upvotes: 30

LuLuGaGa
LuLuGaGa

Reputation: 14418

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)

Upvotes: 21

Related Questions