使用NSUserDefaults保存Button的标记

时间:2014-10-30 18:49:26

标签: ios uibutton nsuserdefaults

大家好,我点击按钮时保存标签有问题:

- (IBAction)addButtonSeconds:(id)sender {


if ([sender tag] == 1) {
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    [standardUserDefaults setObject:@"Off" forKey:@"time"];
    [_editButton setImage:[UIImage imageNamed:@"ВЫКЛ.png"] forState:UIControlStateNormal];
    [_plus setEnabled:YES];
    [_minus setEnabled:YES];
    [_editButton setTag:2];
} else if ([sender tag] == 2){
    [_editButton setImage:[UIImage imageNamed:@"ВКЛ.png"] forState:UIControlStateNormal];
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    [standardUserDefaults setObject:@"ON" forKey:@"time"];
    [_plus setEnabled:NO];
    [_minus setEnabled:NO];
    [_editButton setTag:1];
}

这是初始化方法

 if ([[standartDefaults stringForKey:@"time"]isEqualToString:@"ON"]) {
    self.editButton.tag = 2;
}else{
     self.editButton.tag = 1;
}

如果有人能说我的问题在哪里。谢谢。

1 个答案:

答案 0 :(得分:2)

看起来您期望addButtonSeconds:内的行为与初始化期间的行为不同。

初始化时:

self.editButton.tag == 2; // when "time" is "ON"
self.editButton.tag == 1; // when "time" is not "ON"

addButtonSeconds:

self.editButton.tag == 1; // when "time" is "ON"
self.editButton.tag == 2; // when "time" is not "ON"

尽管如此,我不确定你所写的内容在逻辑上是否有意义或者必须使用tag属性。考虑使用UIButton进行子类化,或者只使用setSelected:的现有isSelectedUIButton

修改:我会根据您的评论为您修复代码。

- (IBAction)addButtonSeconds:(id)sender {
  [_editButton setSelected:![_editButton isSelected]];
  [_plus setEnabled:![_editButton isSelected]];
  [_minus setEnabled:![_editButton isSelected]];
  NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
  [standardUserDefaults setObject:@([_editButton isSelected]) forKey:@"editSelected"];
}

在初始化中:

[_editButton setImage:[UIImage imageNamed:@"ВЫКЛ.png"] forState:UIControlStateNormal];
[_editButton setImage:[UIImage imageNamed:@"ВКЛ.png"] forState:UIControlStateSelected];
[_editButton setImage:[UIImage imageNamed:@"ВКЛ.png"] forState:UIControlStateSelected|UIControlStateHighlighted];
[_editButton setSelected:[[standartDefaults stringForKey:@"editSelected"] boolValue]];