Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force RTL or LTR in SwiftUI

Tags:

ios

swift

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?

like image 243
SinaMN75 Avatar asked Sep 08 '19 18:09

SinaMN75


3 Answers

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.

like image 60
Mojtaba Hosseini Avatar answered Oct 17 '22 13:10

Mojtaba Hosseini


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)
like image 45
LuLuGaGa Avatar answered Oct 17 '22 13:10

LuLuGaGa


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()
            }
        }
    }
like image 2
iTarek Avatar answered Oct 17 '22 11:10

iTarek