Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

button flip help

So I'm trying to make a green button flip over to a red button, then back.

- (IBAction)touchCardButton:(UIButton *)sender
{
    if ([sender.currentBackgroundImage isEqual:@"buttonImageGreen"]) {
        [sender setBackgroundImage:[UIImage imageNamed:@"buttonImageRed"]
                          forState:UIControlStateNormal];
        [sender setTitle:@"duh" forState:UIControlStateNormal];
    }
    else {
        [sender setBackgroundImage:[UIImage imageNamed:@"buttonImageGreen"]
                          forState:UIControlStateNormal];
        [sender setTitle:@"1" forState:UIControlStateNormal];
    }
}

Right now it's not flipping over. I'm pretty sure the problem is with the "isEqual:" method, but I'm not sure what the right syntax is to say "if the button background is green, then make it red.

Any help is much appreciated. Thanks.

2 Answers

hmm maybe try

if ([sender.currentBackgroundImage isEqual:[UIImage imageNamed:@"buttonImageGreen.png"]])

Im pretty sure you have to include the extension to compare two images. you could also try comparing the titles of the button if you have two different titles depending on if its green or red using something like

if ([sender.title isEqualToString:@"someTitle"]) 

its probably easier to set a bool property and use that for comparison of state instead of images/titles

edit: looking over the answers posted here, image comparison is not the way you want to go. As I suggested you should probably find another way of comparing your buttons state using either a bool or possibly the title of the button etc

Thanks Stone.

The first one didn't work, but I think you're right about the second option. Will give that a try.

-