1

按下后如何保存选定的按钮状态?因此,当您在视图控制器之间切换并来到原始视图控制器时,按钮保持按下状态,直到您再次按下它...

- (void)viewDidLoad
{
    [super viewDidLoad];

    addCheck = NO;
    favCheck = NO;
}

- (IBAction)listButton:(id)sender {

    UIImage *removeListImage = [UIImage imageNamed:@"removeList.png"];
    UIImage *addListImage = [UIImage imageNamed:@"addList.png"];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSMutableArray *favoriteviews = [defaults mutableArrayValueForKey:@"favorite_views_key"];

    [defaults setObject:favoriteviews forKey:@"favorite_views_key"];
    [defaults synchronize];

    if (!addCheck) {

        [addList setImage:removeListImage forState:UIControlStateNormal];

        addCheck = YES;

        [favoriteviews addObject:@"Apple"];
        [favoriteviews addObject:@"Banana"];
        [favoriteviews addObject:@"Celery"];
    }

    else if (addCheck) {
        [addList setImage:addListImage forState:UIControlStateNormal];

        addCheck = NO;

        [favoriteviews removeObject:@"Apple"];
        [favoriteviews removeObject:@"Banana"];
        [favoriteviews removeObject:@"Celery"];
    }        
}
4

1 回答 1

0

对于最简单的情况,您可以为控件的两种不同状态(在本例中为按钮)设置图像。并检查每次点击的状态以更改它。例如

if(![myButton isSelected]){
    [myButton setSelected:YES];
    // Do your proceedings when the button is selected here
}
else{
   [myButton setSelected:NO];
   // Do your proceedings when the button is unselected here
}

当您在 中设置按钮时viewDidLoad,只需为这两种状态设置按钮的图像

[addList setImage:addListImage forState:UIControlStateNormal];
[addList setImage:removeListImage forState:UIControlStateSelected];

或者,如果您在界面生成器中设置按钮,您也可以在那里为两种状态设置这些图像。

最好向它添加一些逻辑来持久化某种数据来设置按钮的状态,这取决于它。

于 2013-10-06T04:54:09.023 回答