如何使解锁图像保持不变直到用户没有改变。

时间:2016-05-13 06:15:43

标签: ios checkbox uibutton

我正在UIButton作为复选框工作,当我按下按钮而不是复选框时,选中的图像会出现,再次按下复选框时会出现未选择的图像。如果按下按钮图像会出现,但当我再次回到该视图时它会再次消失。

- (void)viewDidLoad {
     [super viewDidLoad];

     _car.delegate = self;
     _car.keyboardType = UIKeyboardTypeNumberPad;


     [_PreCheck setBackgroundImage:[UIImage imageNamed:@"checkbx_unchecked@2x.png"] forState:UIControlStateNormal];
     [_PreCheck setBackgroundImage:[UIImage imageNamed:@"checkbx@2x.png"] forState:UIControlStateSelected];
     [_PreCheck addTarget:self action:@selector(checkboxSelected:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)didReceiveMemoryWarning {
     [super didReceiveMemoryWarning];
}

-(void)checkboxSelected:(id)sender
{
    if ((checkBoxSelected = !checkBoxSelected)) {
        [_PreCheck setSelected:checkBoxSelected];
        NSLog(@"selected");
        NSString *selected = @"selected";
        NSUserDefaults *select = [NSUserDefaults standardUserDefaults];
        [select setObject:selected forKey:@"checkboxselected"];
        [select synchronize];
    }
    else
    {
        NSLog(@"not selected");
        [_PreCheck setSelected:notselected];
    }
}

2 个答案:

答案 0 :(得分:3)

根据您发布的代码,您必须检查ViewDidLoad当前的NSUserDefaults是否已根据它选择存储值首先需要设置按钮检查取消选中图像。以下是您的viewDidLoad代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    _car.delegate = self;
    _car.keyboardType = UIKeyboardTypeNumberPad;

     NSString *state = [[NSUserDefaults standardUserDefaults] stringForKey:@"btnstate"];

    if([state isEqualToString:@"selected"])
    {
     [_PreCheck setBackgroundImage:[UIImage imageNamed:@"checkbx@2x.png"] forState:UIControlStateNormal];
        [_PreCheck setSelected:YES];
    }
    else
    {
        [_PreCheck setBackgroundImage:[UIImage imageNamed:"checkbx_unchecked@2x.png"] forState:UIControlStateNormal];
        [_PreCheck setSelected:NO];

    }

    [_PreCheck addTarget:self action:@selector(checkboxSelected:) forControlEvents:UIControlEventTouchUpInside];

}

现在设置check-uncheck的方法,如下所示:

-(void)checkboxSelected:(UIButton*)sender
{
     sender.selected = !sender.selected;
    if([sender isSelected])
    {
        [_PreCheck setBackgroundImage:[UIImage imageNamed:@"checkbx@2x.png"] forState:UIControlStateNormal];

       [[NSUserDefaults standardUserDefaults] setValue:@"selected" forKey:@"btnstate"];

    }
    else
    {
        [_PreCheck setBackgroundImage:[UIImage im ageNamed:@"checkbx_unchecked@2x.png"] forState:UIControlStateNormal];
     [[NSUserDefaults standardUserDefaults] setValue:@"notselected" forKey:@"btnstate"];
    }

}

希望工作还是你。只需用我发布的代码替换您的代码,无需进行其他更改。

答案 1 :(得分:1)

将按钮状态存储在NSUSerDefaults

然后在viewDidLoad中获取状态并基于该加载图像。

- (void)viewDidLoad
{
    // Your code

    // get selected state from user defaults.
     BOOL selected = [[NSUserDefaults standardUserDefaults] boolForKey:@"buttonstateKey"];
     if (selected)
     {
      // set selected image
     }
     else 
     {
     // set regular image
     }
}