Reputation: 91
I have several Buttons. The Buttons images are a circle or a X. I want to check the actually Buttons image. I tryed it with the following code, but i get always "_cell00 != X"
the Buttons image is set by
[_cell00 setImage: [UIImage imageNamed:[NSString stringWithFormat:@"Dot_X.png"]] forState:UIControlStateNormal];
and heres my check code:
if ([_cell00 imageForState:UIControlStateNormal] == [UIImage imageNamed:[NSString stringWithFormat:@"Dot_X.png"]]) {
NSLog(@"CELL00 = X");
}
or:
if ([_cell00 imageForState:UIControlStateNormal] != [UIImage imageNamed:[NSString stringWithFormat:@"Dot_X.png"]]) { NSLog(@"CELL00 != X");
}
whats the problem in my case?
Upvotes: 0
Views: 42
Reputation: 8402
okay, the UIImage
method [UIImage imageNamed:[NSString stringWithFormat:@"Dot_X.png"]]
always creates a new instance of image object, come to your code
UIImage *image_X = [UIImage imageNamed:[NSString stringWithFormat:@"Dot_X.png"]]; //<UIImage: 0x7a041ae0> an example lets say
[_cell00 setImage:image_X forState:UIControlStateNormal];
in the above method u are setting the new instance of image for buttons normal state lets say it is <UIImage: 0x7a041ae0>
in your comparison method,
UIImage *image_X = [UIImage imageNamed:[NSString stringWithFormat:@"Dot_X.png"]]; //<UIImage: 0x78e02e90> it create a brand new image
if ([_cell00 imageForState:UIControlStateNormal] == image_X)
{
NSLog(@"CELL00 = X");
}
in the above code, u are once again creating the new instance, which is different than the one u already set for button _cell00
the image is <UIImage: 0x78e02e90>
it is totally different, thats the it always goes to "_cell00 != X"
so instead u can do like below,
while setting the images for button set all the images for button,
[_cell00 setImage: [UIImage imageNamed:[NSString stringWithFormat:@"Dot_X.png"]] forState:UIControlStateNormal];
[_cell00 setImage: [UIImage imageNamed:[NSString stringWithFormat:@"Dot_X.png"]] forState:UIControlStateHighlighted];
[_cell00 setImage: [UIImage imageNamed:[NSString stringWithFormat:@"Dot_O.png"]] forState:UIControlStateSelected];
and while comparing the button, just check weather that button is selected or not if it not selected then select it, if not just toggle back, for example, your comparison method look something like below
if(_cell00.selected)
{
_cell00.selected = NO;
NSLog(@"CELL00 = X");
}
else
{
_cell00.selected = YES;
NSLog(@"CELL00 != X");
}
Upvotes: 1
Reputation: 5436
Just use the backgroundImageForState
method of UIButton
which returns the UIImage
- (UIImage *)backgroundImageForState:(UIControlState)state
Like below code:
if ([[_cell00 backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:[NSString stringWithFormat:@"Dot_X.png"]]]){
// NSLog(@"CELL00 = X");
} else{
// Something
}
OR
if ([[_cell00 backgroundImageForState:UIControlStateNormal] == [UIImage imageNamed:[NSString stringWithFormat:@"Dot_X.png"]]]) {
//
}
else{
}
Upvotes: 1