我进行了彻底的研究,但似乎没有找到我正在寻找的答案。希望有人能帮忙。
我的应用程序中有多个 View Controller ,其中一个是“选项” View ,用户可以在其中通过分段控件更改某些设置,例如背景颜色。单击后,用户单击按钮将他们的偏好颜色保存到 NSUserDefaults。这非常有效,下次打开应用程序时,仍会选择正确的颜色。但仅在选项 View Controller 中。
我怎样才能让这个选定的背景颜色加载到我的其他 View Controller 中?我似乎没有通过将它实现到我的其他 View 的 ViewDidLoad 中来运行它,就像我在选项 View 中所做的那样(见下文)。
我在options.m中的代码如下:
- (IBAction)changeColor {
switch (colorControl.selectedSegmentIndex) {
case 0:
[colorView setBackgroundColor:[UIColor redColor]];
break;
case 1:
[colorView setBackgroundColor:[UIColor blackColor]];
break;
case 2:
[colorView setBackgroundColor:[UIColor brownColor]];
break;
default:
break;
}
}
- (IBAction)saveDefaultColor {
int defaultColorInteger = colorControl.selectedSegmentIndex;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:defaultColorInteger forKey:@"defaultColor"];
[userDefaults synchronize];
}
以上是控制和保存按钮。在我的 ViewDidLoad 中,我包含了以下内容:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
int defaultColorInteger = [userDefaults integerForKey:@"defaultColor"];
[colorControl setSelectedSegmentIndex:defaultColorInteger];
switch (colorControl.selectedSegmentIndex) {
case 0:
[colorView setBackgroundColor:[UIColor redColor]];
break;
case 1:
[colorView setBackgroundColor:[UIColor blackColor]];
break;
case 2:
[colorView setBackgroundColor:[UIColor brownColor]];
break;
default:
break;
这完全符合我的要求,但我不能让它在我的其他 View 中工作。 谁能帮我解决我似乎缺少的东西?非常感谢
最佳答案
我认为您需要检查其他 View 中的键值,因为 NSUserDefaults 为整个应用程序而不是单个 View 保存数据。可能是您没有正确放置 key 。
关于ios - Xcode 在多个 View Controller 中加载 NSUserDefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21111130/