我是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 ");
}
}
任何人都可以帮助我。在此先感谢
答案 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方式执行此操作。设置控制状态是一个很好的方法。但如果UIControlStateSelected
为YES
,它会为按钮设置不需要的叠加背景。 :
- (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]];
}
}