ios - 在 NSUserDefaults 上更改语言后更新 UI

标签 ios ios7 internationalization

我创建了一个语言选择屏幕,用户可以在其中选择应用 (iPad) 的首选语言。

我这样提交语言更改:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"fr"] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];

除了它需要重新启动应用程序以使用户界面采用新的语言设置外,它运行良好。根据 Apple 的文档:

To detect when changes to a preference value occur, apps can also register for the notification NSUserDefaultsDidChangeNotification. The shared NSUserDefaults object sends this notification to your app whenever it detects a change to a preference located in one of the persistent domains. You can use this notification to respond to changes that might impact your user interface. For example, you could use it to detect changes to the user’s preferred language and update your app content appropriately.

看来我需要注册通知 NSUserDefaultsDidChangeNotification 并更新我的 UI。哪个类(class)应该收听通知?知道代码是什么样的吗?我的应用程序基于 SKScenes 和 Sprite Kit 对象,而不是 xib 和 UIViewControllers。

最佳答案

所有通知都可以通过监视 NSNotificationCenter 检测到:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
       selector:@selector(userDefaultsChange:)  
           name:NSUserDefaultsDidChangeNotification
         object:nil];

- (void)userDefaultsChange:(NSNotification *)notification {
     //update UI to new language here
}    

在创建类时添加观察器,并记住在删除类时必须将其删除。

[[NSNotificationCenter defaultCenter] removeObserver:self];

关于ios - 在 NSUserDefaults 上更改语言后更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21928032/

相关文章:

iphone - 如何从基于 map 的 iPhone 应用程序播放音频文件?

ios - 将 UITextField 添加到导航项的标题 View

iphone - 在导航栏上方添加 View

正则表达式选择 { 和 } 之间的所有输入

ios - UIWebView 根据本地语言使用 Google 进行搜索

ios - UINavigtionController Nib 的顶部栏黑色不透明不在 UIViewController 上显示黑色

c# - 使用 MonoTouch 以编程方式将 UITextField 添加到 UIView

ios7 - 获取 iOS 7 范围内的 SSID

testing - 移动应用测试

javascript - 如何在 javascript 中使用 ICU 字符串获取日期的 ISO8601 表示?