在 SwiftUI 中强制 RTL 或 LTR
Force RTL or LTR in SwiftUI
我知道 SwiftUI 根据设备的系统语言改变应用程序的方向。但是有没有办法忽略系统语言并强制应用程序始终为 RTL 或 LTR?
您可以在场景委托中设置布局方向:
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()
}
}
或使用此修饰符手动禁用某些视图的方向更改:
.flipsForRightToLeftLayoutDirection(true)
您可以将应用程序的默认语言设置为 从右到左,例如 info.plist
中的 Persian
或使用其他方法:
如果您需要强制视图,只需在您喜欢的任何视图上应用此修饰符即可:
.environment(\.layoutDirection, .rightToLeft)
您可以申请SceneDelegate
中的ContentView()
,使其对所有子视图可用。
我尝试了所有方法来强制 SwiftUI 成为 RTL 阿拉伯语,例如...
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)
}
}
}
但是如果你使用 NavigationView 这种方式会导致很多错误
最好的解决办法是...
import SwiftUI
@main
struct MyApp: App {
init() {
UserDefaults.standard.set(["ar"], forKey: "AppleLanguages")
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
我知道 SwiftUI 根据设备的系统语言改变应用程序的方向。但是有没有办法忽略系统语言并强制应用程序始终为 RTL 或 LTR?
您可以在场景委托中设置布局方向:
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()
}
}
或使用此修饰符手动禁用某些视图的方向更改:
.flipsForRightToLeftLayoutDirection(true)
您可以将应用程序的默认语言设置为 从右到左,例如 info.plist
中的 Persian
或使用其他方法:
如果您需要强制视图,只需在您喜欢的任何视图上应用此修饰符即可:
.environment(\.layoutDirection, .rightToLeft)
您可以申请SceneDelegate
中的ContentView()
,使其对所有子视图可用。
我尝试了所有方法来强制 SwiftUI 成为 RTL 阿拉伯语,例如...
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)
}
}
}
但是如果你使用 NavigationView 这种方式会导致很多错误 最好的解决办法是...
import SwiftUI
@main
struct MyApp: App {
init() {
UserDefaults.standard.set(["ar"], forKey: "AppleLanguages")
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}