在project.pbxproj中,我将developmentRegion更改为ar,以在整个应用程序中强制使用阿拉伯语言和RTL布局。除了本例中的菜单视图内容之外,一切看起来都不错:
import SwiftUI
struct ContentView: View {
@State private var selectedTime: Int = 0
var body: some View {
Form {
Picker("", selection: $selectedTime) {
Text("صباحاً").tag(0)
Text("مساءً").tag(1)
}
.labelsHidden()
.pickerStyle(SegmentedPickerStyle())
Menu {
Button("السبت", action: {})
Button("الأحد", action: {})
Button("الاثنين", action: {})
Button("الثلاثاء", action: {})
Button("الاربعاء", action: {})
Button("الخميس", action: {})
Button("الجمعة", action: {})
} label: {
Label("اليوم", systemImage: "calendar")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.preferredColorScheme(.dark)
}
}
菜单内的按钮标签翻转。
实现此目的的唯一方法是通过设置更改语言并重新启动应用程序。
File -> New -> File -> Settings Bundle
根据需要删除无用的设置
18 August 2021
)UserDefaults.standard.set(["ar"], forKey: "AppleLanguages")
但是!
exit()
,则使用
ar
模拟器不断缓存设置。因此,您可能会遇到无法查看当前设置的问题。尝试在测试项目中测试流程并在实际项目中实现结果。
只需添加
init() {
UserDefaults.standard.set(["ar"], forKey: "AppleLanguages")
}
这里是完整的代码
import SwiftUI
struct ContentView: View {
init() {
UserDefaults.standard.set(["ar"], forKey: "AppleLanguages")
}
@State private var selectedTime: Int = 0
var body: some View {
Form {
Picker("", selection: $selectedTime) {
Text("صباحاً").tag(0)
Text("مساءً").tag(1)
}
.labelsHidden()
.pickerStyle(SegmentedPickerStyle())
Menu {
Button("السبت", action: {})
Button("الأحد", action: {})
Button("الاثنين", action: {})
Button("الثلاثاء", action: {})
Button("الاربعاء", action: {})
Button("الخميس", action: {})
Button("الجمعة", action: {})
} label: {
Label("اليوم", systemImage: "calendar")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.preferredColorScheme(.dark)
}
}
唯一对我有用的东西(特别是我已将 SwiftUI 添加到 UIKit 项目中)是:
对存在镜像问题的视图调用
.flipsForRightToLeftLayoutDirection(enabled:Bool)
。如果布局为 true
,则通过 RTL
。
类似这样的:
// Step 1: Create View extension for RTL fix
extension View {
func fixRtl(_ layoutDirection: LayoutDirection) -> some View {
return self.flipsForRightToLeftLayoutDirection(layoutDirection == LayoutDirection.rightToLeft)
}
}
// Step 2: Add layoutDirection variable to your SwiftUI view
struct ContentView: View {
@Environment(\.layoutDirection) var layoutDirection
var body: some View {
VStack {
// Step 3: Apply fixRtl extension to Text views or their containers
Text("RTL TEXT النص بالعربي")
.fixRtl(layoutDirection)
.padding()
HStack {
// Applying fixRtl to a container
VStack {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
.fixRtl(layoutDirection)
.padding()
// Applying fixRtl directly to a Text view
Text("Another RTL TEXT النص بالعربي")
.fixRtl(layoutDirection)
.padding()
}
}
}
}
这是我如何让它在我的应用程序中工作:
如果只执行此步骤,RTL 布局将在模拟器中正确显示,但不会在真实设备上显示(除非设备的语言是 RTL)
这将强制应用程序的首选语言始终保留为您的 RTL 语言。
@main
struct AppName: App {
init() {
UserDefaults.standard.set(["ar"], forKey: "AppleLanguages")
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}