我创建了一个语言选择屏幕,用户可以在其中选择应用 (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/