简体   繁体   中英

can't change image of uibutton after pressing other buttons

i have 2 buttons that keep with the pressed image even when they are released, until the other button is pressed, then the image returns to the normal image my code is this:

    - (IBAction)button1_touch:(UIButton *)sender
{

    [Button2 setImage:[UIImage imageNamed:@"b2Released.png"] forState:UIControlStateNormal];

    [Button1 setImage:[UIImage imageNamed:@"b1Pressed.png"] forState:UIControlStateNormal];    
}

- (IBAction)button2_touch:(UIButton *)sender
{
    [Button1 setImage:[UIImage imageNamed:@"b1Released.png"] forState:UIControlStateNormal];

    [Button2 setImage:[UIImage imageNamed:@"b2Pressed.png"] forState:UIControlStateNormal]; 


}

the code above works fine when the app starts, the behavior is the expected pressing both buttons, images change correctly, but when i press other button than those two, the "Button2" once it gets the "B2Pressed.png" image, it never returns to its released image, i wrote a nslog in button1_touch and it gets printed as expected, and the Button1 gets its pressed image, but the Button2 is not getting its released image, is like the method setImage of UiButton gets broken when i press other button than those two, other buttons are independent from those two, for me this behavior has absolutely no sense at all, could it be xcode broken? i am working on xcode 7.2

EDIT: the problem occurs when i press another button only if that button has a action selector assigned to it (UIControlEventTouchUpInside).

You can use selected state of UIButton for this purpose:

- (void)viewDidLoad {
    // ...
    // the place where you do buttons setup
    [button1 setImage:[UIImage imageNamed:@"b1Released"] forState:UIControlStateNormal];
    [button1 setImage:[UIImage imageNamed:@"b1Pressed"] forState:UIControlStateSelected];
    [button2 setImage:[UIImage imageNamed:@"b2Released"] forState:UIControlStateNormal];
    [button2 setImage:[UIImage imageNamed:@"b2Pressed"] forState:UIControlStateSelected];
}    

- (IBAction)firstButtonTouch:(UIButton *)sender {
    button1.selected = YES;
    button2.selected = NO;
}

- (IBAction)secondButtonTouch:(UIButton *)sender {
    button1.selected = NO;
    button2.selected = YES;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM