是否有使用localizableTextProvider(withStringsFileFormatKey:,textProviders :)设置复杂功能的官方示例?我可以在生成SampleTemplate时填充文本提供程序,但每当我尝试使用getTimelineEntries生成一个由localizableTextProvider生成的文本提供程序时,结果总是空白,没有文本。
示例(仅支持.utilitarianLarge):
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
// Call the handler with the current timeline entry
let template = CLKComplicationTemplateUtilitarianLargeFlat()
template.textProvider = CLKTextProvider.localizableTextProvider(
withStringsFileFormatKey: "testComplication",
textProviders: [
CLKSimpleTextProvider(text: "Hello"),
CLKSimpleTextProvider(text: "World")
]
)
handler(CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template))
}
和sampleTemplate一样
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
switch complication.family {
case .utilitarianLarge:
let template = CLKComplicationTemplateUtilitarianLargeFlat()
template.textProvider = CLKTextProvider.localizableTextProvider(
withStringsFileFormatKey: "testComplication",
textProviders: [
CLKSimpleTextProvider(text: "Hi"),
CLKSimpleTextProvider(text: "World")
]
)
handler(template)
default:
handler(nil)
}
}
用ckcomplication.strings作为
"testComplication" = "%@ %@";
样本模板将始终显示文本“Hi World”,而getCurrentTimelineEntry的结果将始终显示空复杂。
有没有人以这种方式组成文本提供者?
看来这个API在Swift中被破坏了(截至4.2)。我使用Objective C类别解决了这个问题。从here公然被盗
CLKTextProvider + NNNCompoundTextProviding.h
@interface CLKTextProvider (NNNCompoundTextProviding)
+ (nonnull CLKTextProvider *)nnn_textProviderByJoiningProvider:(nonnull CLKTextProvider *)provider1 andProvider:(nonnull CLKTextProvider *)provider2 withString:(nullable NSString *)joinString;
@end
CLKTextProvider + NNNCompoundTextProviding.m
@implementation CLKTextProvider (NNNCompoundTextProviding)
+ (nonnull CLKTextProvider *)nnn_textProviderByJoiningProvider:(nonnull CLKTextProvider *)provider1 andProvider:(nonnull CLKTextProvider *)provider2 withString:(nullable NSString *)joinString
{
NSString *textProviderToken = @"%@";
NSString *formatString;
if (joinString != nil) {
formatString = [NSString stringWithFormat:@"%@%@%@",
textProviderToken,
joinString,
textProviderToken];
}
else {
formatString = [NSString stringWithFormat:@"%@%@",
textProviderToken,
textProviderToken];
}
return [self textProviderWithFormat:formatString, provider1, provider2];
}
@end