按下后更改按钮图像,然后在ios中释放

时间:2018-01-12 16:50:44

标签: objective-c image button nsuserdefaults

我有一个带图像的按钮。按下此按钮时,必须更改图像。再次按下该按钮时,应将其更改回原始图像。 更改视图控制器时,应保持更改此图像。

1 个答案:

答案 0 :(得分:1)

UIView添加按钮。

进入情节提要 xib 或按钮的位置检查窗口,然后将图像设置为选中,将图像设置为未选中

在控制器中创建一个IBAction,并将按钮连接到该操作。

-(IBAction) toggleUIButtonImage:(id)sender{
      if ([sender isSelected]) {
         [sender setImage:unselectedImage forState:UIControlStateNormal];
         [sender setSelected:NO];

         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
         [defaults setValue:@"no" forKey:@"buttonSelected"];
         [defaults synchronize];
      } else {
         [sender setImage:selectedImage forState:UIControlStateSelected];
         [sender setSelected:YES];

         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
         [defaults setValue:@"yes" forKey:@"buttonSelected"];
         [defaults synchronize];
      }
  } 

IBAction链接到您的按钮

然后,为了知道它是否已被选中,您需要在NSUserDefaults方法中查询viewDidLoad

- (void) querySelected {
    NSString *selected = [[NSUserDefaults standardUserDefaults] objectForKey:@"buttonSelected"];

    if ([selected isEqualToString: @"yes"]) {
        [sender setImage:selectedImage forState:UIControlStateSelected];
        [sender setSelected:YES];
    } else {
        [sender setImage:unselectedImage forState:UIControlStateNormal];
        [sender setSelected:NO];
    }
}