Button按两次颜色的方式应该如何使用NSUSerDefaults更改

时间:2014-11-20 06:18:28

标签: ios objective-c uibutton nsuserdefaults

我是XCode的新手。我和NSUserDefaults一起使用,即使它没有按照我要求的方式进行操作如果我在该按钮上单击一次它应该将颜色更改为绿色如果我再次按下它应该更改颜色为黑色。

我的代码在这里 -

- (IBAction)subscribeButtonAction:(id)sender {
    if (count == 0) {
        [_subscribeButtonObj setBackgroundColor:[UIColor greenColor]];
        greenStr=[NSString stringWithFormat:@"green"];
        NSUserDefaults *greendefults=[NSUserDefaults standardUserDefaults];
        [greendefults setValue:greenStr forKey:@"greencolor"];
        [greendefults synchronize];
        ///
        count++;
    } else if(count == 1){
        [_subscribeButtonObj setBackgroundColor:[UIColor blueColor]];
        blackStr=[NSString stringWithFormat:@"black"];
        NSUserDefaults *blackDefaults=[NSUserDefaults standardUserDefaults];
        [blackDefaults setValue:blackStr forKey:@"blackcolor"];
        [blackDefaults synchronize];
        //count = 0;
    }
}

ViewWillAppear我写了这样的代码 -

-(void)viewWillAppear:(BOOL)animated
{
    //count = 0;
    if ([[NSUserDefaults standardUserDefaults] stringForKey:@"greencolor"]) {
        NSLog(@"change the button to green color %@",[[NSUserDefaults standardUserDefaults] stringForKey:@"greencolor"]);
    } else {
        NSLog(@"change the button to blackcolor ");
    }
}

任何人都可以帮助我。在此先感谢

2 个答案:

答案 0 :(得分:1)

不需要NSUserDefaults来实现这一点。用UIButton的控制状态处理它很简单,

  • UIControlStateNormal
  • UIControlStateSelected

例如,

- (IBAction)changeColor:(id)sender {
    UIButton *button = (UIButton *)sender;
    if (button.selected) { // If selected will change the color into Red
        button.backgroundColor = [UIColor redColor];
        [button setSelected:NO];
    } else {
        button.backgroundColor = [UIColor greenColor];
        [button setSelected:YES];
    }
}

并且,请记住,您最初可以更改按钮的状态,例如

[myButton setSelected:YES];

viewDidLoad

中分配此代码

干杯!!

答案 1 :(得分:0)

如果您想以NSUserDefault方式执行此操作。设置控制状态是一个很好的方法。但如果UIControlStateSelectedYES,它会为按钮设置不需要的叠加背景。 :

- (IBAction)btnAction:(id)sender {
    NSUserDefaults *color=[NSUserDefaults standardUserDefaults];
    if (count == 0) {
        [self.btnOutlet setBackgroundColor:[UIColor greenColor]];
        [color setValue:@"green" forKey:@"color"];

    }else if(count == 1){
        [self.btnOutlet setBackgroundColor:[UIColor blueColor]];
        [color setValue:@"blue" forKey:@"color"];

    }
    count = !count;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    count = 0;

    if([[[NSUserDefaults standardUserDefaults] valueForKey:@"color"] isEqualToString:@"green"]){ // been used
        [self.btnOutlet setBackgroundColor:[UIColor greenColor]];
    }else if([[[NSUserDefaults standardUserDefaults] valueForKey:@"color"] isEqualToString:@"blue"]){
        [self.btnOutlet setBackgroundColor:[UIColor blueColor]];
    }else{ // first time
        [self.btnOutlet setBackgroundColor:[UIColor yellowColor]];
    }
}