保存/加载UIColor用户选择默认值

时间:2014-11-16 03:45:24

标签: objective-c xcode save uicolor

从下面的屏幕截图中我可以看到,我有一个倒计时时钟,我允许用户更改UI上按钮和标签的颜色。我的问题是,我希望用户能够保存他们的颜色设置,但我无法弄清楚位置和顺序。我知道这个问题已在这里得到解答:Saving UIColor to and loading from NSUserDefaults

然而,我想我不会"得到它"并需要额外的帮助。因此,下面屏幕截图中的每种颜色都有这样的编码:

-(IBAction)red
{
    [_enterDateOutlet setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_backButtonOutlet setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    _yearsLabel.textColor = [UIColor redColor];
    _daysLabel.textColor = [UIColor redColor];
    _hoursLabel.textColor = [UIColor redColor];
    _minLabel.textColor = [UIColor redColor];
    _secLabel.textColor = [UIColor redColor];
    minuteProgessView.theme.labelColor = [UIColor redColor];
    secondProgessView.theme.labelColor = [UIColor redColor];
    hourProgessView.theme.labelColor = [UIColor redColor];
    dayProgessView.theme.labelColor = [UIColor redColor];
    yearProgessView.theme.labelColor = [UIColor redColor];
}

我的问题是我是否将此代码放在每个“颜色操作”按钮的末尾(我有7种颜色)?

NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject: color];
[[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"color1"];

因为我认为我应该这样做,然后我将其添加到我的View Did Load Method:

NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];

结果出现红色错误,因为"颜色"是未宣布的标识符。

我真的很感激帮助,我是新手,我花了最近2个小时试图解决这个问题。谢谢。 Screenshot

1 个答案:

答案 0 :(得分:2)

我认为你可以做这样的事情。创建一个方法,该方法将调用函数来设置颜色并将颜色传递给它。在此方法中,您将颜色保存为用户默认值。当用户返回viewDidLoad中的应用时,它将检索颜色并进行设置。我的Xcode此刻正在崩溃所以我无法运行它。如果您正在寻找,请告诉我。

-(IBAction)red
{

    [self setAllTo:[UIColor redColor]];
}
-(IBAction)green
    {

        [self setAllTo:[UIColor greenColor]];
    }

-(void)setAllTo:(UIColor *)color
{
    [_enterDateOutlet setTitleColor:color forState:UIControlStateNormal];
        [_backButtonOutlet setTitleColor:color forState:UIControlStateNormal];
        _yearsLabel.textColor = color;
        _daysLabel.textColor = color;
        _hoursLabel.textColor = color;
        _minLabel.textColor = color;
        _secLabel.textColor = color;
        minuteProgessView.theme.labelColor = color;
        secondProgessView.theme.labelColor = color;
        hourProgessView.theme.labelColor = color;
        dayProgessView.theme.labelColor = color;
        yearProgessView.theme.labelColor = color;
        NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color];
        [[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"myColor"];
        [[NSUserDefaults standardUserDefaults] synchronize]         
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
    UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
    if(color){
          [self setAllTo:color];
    }else{
         [self setAllTo:[UIColor whiteColor]]; //default color
    }
}