gpt4 book ai didi

ios - 如何在 IOS 运行时切换到语言后获取本地化的 Storyboard字符串?

转载 作者:可可西里 更新时间:2023-11-01 04:46:15 27 4
gpt4 key购买 nike

我有以下代码来切换语言运行时:

-(void) switchToLanguage:(NSString *)lang{
self.language = lang;
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:self.language, nil]
forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

我有一个检索本地化字符串的辅助函数:

+(NSString *) getLocalizedString:(NSString *)key{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *path = [[NSBundle mainBundle] pathForResource:@"Localizable"
ofType:@"strings"
inDirectory:nil
forLocalization:appDelegate.language];

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return [dict objectForKey:key];
}

这是有效的。我的 Storyboard也已本地化,但当我切换到另一种语言时它们并没有改变。

如何获取 Storyboard字符串的本地化值?

最佳答案

在运行时更改语言有点棘手。

这是我在这个小类(class)的帮助下使用过的最好的方法:

语言.m:

#import "Language.h"

@implementation Language

static NSBundle *bundle = nil;

+(void)initialize {
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString *current = [languages objectAtIndex:0];
[self setLanguage:current];

}

+(void)setLanguage:(NSString *)l
{
NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ];
bundle = [NSBundle bundleWithPath:path];
}

+(NSString *)get:(NSString *)key alter:(NSString *)alternate
{
return [bundle localizedStringForKey:key value:alternate table:nil];
}

@end

语言.h:

import <Foundation/Foundation.h>

@interface Language : NSObject
+(void)setLanguage:(NSString *)l;
+(NSString *)get:(NSString *)key alter:(NSString *)alternate;

@end

当你想改变语言时:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", @"de", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
[Language setLanguage:@"en"];

[(AppDelegate *)[[UIApplication sharedApplication] delegate] window].rootViewController = [self.storyboard instantiateInitialViewController];

当你想设置一个字符串时:

[self.someButton setTitle:[Language get:@"Some Button Text" alter:nil] forState:UIControlStateNormal];

关于ios - 如何在 IOS 运行时切换到语言后获取本地化的 Storyboard字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26496404/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com