在Widget中configurationDisplayName、description等小组件名称和描述修饰符,以及WidgetView的文本内容,如果需要实现本地化。需要通过本地化字符串文件进行实现。

首先,需要在项目中创建一个本地化字符串文件(Localizable.xcstrings)。这个文件将包含所有需要本地化的文本。
在 Xcode 中,右键点击项目或文件夹,选择 New File…。
选择 Strings Catalog,然后点击 Next。

将文件命名为 Localizable.xcstrings,然后点击 Create。
在项目导航器中选中 Localizable.xcstrings文件,然后点击左侧添加本地化的语言。

跟主应用的本地化方式一致,点击加号添加本地化键和本地化内容。
在Widget中,configurationDisplayName和description的文本跟Localizable.xcstrings文件中的本地化键对应。
struct BankletWidget: Widget {
@State private var background: String = "bg0"
let kind: String = "BankletWidget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: SimpleProvider()) { entry in
BankletWidgetEntryView(entry: entry)
.containerBackground(for: .widget) {
Image("WidgetBackground")
}
}
.supportedFamilies([.systemSmall])
.configurationDisplayName("Progress widget") // 小组件的显示名称
.description("Shows the current progress percentage of the piggy bank.") // 小组件的描述
.disfavoredLocations([.lockScreen], for: [.systemSmall, .systemMedium])
}
}
View文件的本文也同样适用于本地化键:
struct BankletWidgetBackgroundView : View {
var entry: SimpleProvider.Entry
var body: some View {
ZStack {
Image(background)
.resizable()
.scaledToFill()
Text("Progress widget") // 需要本地化的文本
.foregroundColor(.black)
}
}
}
全部设置完成后,如果运行会发现Xcode报错:
/Users/fangjunyu.com/Documents/iOS开发/iOS应用-存钱猪猪/存钱猪猪/BankletWidget/Localizable.xcstrings:1:1 Cannot have multiple Localizable.xcstrings files in same target.
在 iOS 项目中,Localizable.xcstrings 文件是通过 Xcode 自动生成的本地化文件,通常它们会被关联到一个特定的 target。如果在主应用和 Widget 项目中都创建了 Localizable.xcstrings 文件,并且这两个 target 尝试使用相同的文件,Xcode 会报错,因为同一 target 不能有多个相同名称的本地化文件。
解决方法:确保每个 target 有独立的本地化文件:可以为 Widget 创建一个单独的本地化文件,并将其仅与 Widget target 关联。
在Widget项目中找到Localizable.xcstrings文件,然后点击Xcode右侧边栏,找到Target Membership,只勾选Widget项目。

再次运行后,项目正常编译通过并且运行成功。
最后,在真机的日语环境下,组件列表以及组件文本内容全部实现本地化。
