iOS App Intent本地化:封装LocalizedStringResource失效求助
iOS App Intent 本地化封装失效的解决办法
问题分析
核心原因是:App Intent 的本地化元数据是编译时静态解析的。当通过静态方法/属性返回 LocalizedStringResource 实例时,编译器无法追踪到内部指定的 table 参数,只能回退使用 Intent 类名作为默认表名;而直接赋值的方式能让编译器在编译时直接识别到 table 参数,因此有效。
解决方案:使用 @propertyWrapper 包装
通过自定义属性包装器,让编译器能在编译时解析到指定的表名信息,从而正确读取 AppIntents.strings 中的字符串。
1. 定义属性包装器
@available(iOS 16, *) @propertyWrapper struct AppIntentLocalized { let key: String.LocalizationValue // 包装后的值自动指定表名为 AppIntents var wrappedValue: LocalizedStringResource { LocalizedStringResource(key, table: "AppIntents") } init(_ key: String.LocalizationValue) { self.key = key } }
2. 在 Intent 中使用
@available(iOS 16, *) struct ExampleIntent: AppIntent { // 使用自定义包装器,自动关联 AppIntents 表 @AppIntentLocalized("localization.key") static var title: LocalizedStringResource func perform() async throws -> some IntentResult { return .result() } }
替代方案:链式扩展调用
如果你更偏好扩展的方式,可以给 String.LocalizationValue 增加扩展,让编译器能直接识别表名:
@available(iOS 16, *) extension String.LocalizationValue { var appIntent: LocalizedStringResource { LocalizedStringResource(self, table: "AppIntents") } }
在 Intent 中使用:
static var title: LocalizedStringResource = "localization.key".appIntent
原理说明
这两种方案的核心是让编译器在编译阶段就能获取到 table 的具体值,而不是等到运行时通过方法/属性返回实例。App Intent 的本地化系统依赖编译时的静态分析来收集字符串信息,只有能被静态解析的参数才能被正确识别。
内容的提问来源于stack exchange,提问作者Bram
相关产品推荐
相关产品推荐

