Reputation: 455
I am using UIButton with xib backgroundImage is check_box_off.png, while clicking the atmbtn backgroundImage change to check_box_on.png meanwhile NSLog printing yesString and again clicking atmbtn there is no change in backgroundImage same check_box_on.png meanwhile NSLog Printing same yesString only.. again and again clinking the atmbutton same only happening..
- (IBAction)atmAction:(id)sender{
if( [atmbtn backgroundImageForState:UIControlStateNormal] ==
[UIImage imageNamed:@"check_box_on.png"] ) {
[atmbtn setImage:[UIImage imageNamed:@"check_box_off.png"]
forState:UIControlStateNormal];
noString = @"No";
NSLog(@"atm=%@",noString);
} else if( [atmbtn backgroundImageForState:UIControlStateNormal] ==
[UIImage imageNamed:@"check_box_off.png"]) {
[atmbtn setImage:[UIImage imageNamed:@"check_box_on.png"]
forState:UIControlStateNormal];
yesString = @"Yes";
NSLog(@"atm = %@",yesString);
}
}
output:
NSLog Print:
atm=Yes
atm=Yes
atm=Yes
how Could I resolve this? Please Share your Ideas.
Upvotes: 0
Views: 1286
Reputation: 31311
Set a BOOL variable instead of if condition
.h file
BOOL _isClicked;
.m file
-(IBAction)atmAction:(id)sender{
if(!isClicked){
[atmbtn setImage:[UIImage imageNamed:@"check_box_off.png"]
forState:UIControlStateNormal];
_isClicked = YES;
} else {
[atmbtn setImage:[UIImage imageNamed:@"check_box_on.png"]
forState:UIControlStateNormal];
_isClicked = NO;
}
}
Upvotes: 0
Reputation: 3529
Hi try isEqual
method rather then ==
because you are comparing objects not values. Try this:
-(IBAction)atmAction:(id)sender{
if([[atmbtn imageForState:UIControlStateNormal]
isEqual:[UIImage imageNamed:@"check_box_on.png"]] ) {
[atmbtn setImage:[UIImage imageNamed:@"check_box_off.png"]
forState:UIControlStateNormal];
noString = @"No";
NSLog(@"atm = %@",noString);
} else if( [[atmbtn imageForState:UIControlStateNormal]
isEqual:[UIImage imageNamed:@"check_box_off.png"]] ){
[atmbtn setImage:[UIImage imageNamed:@"check_box_on.png"]
forState:UIControlStateNormal];
yesString = @"Yes";
NSLog(@"atm = %@",yesString);
}
}
Upvotes: 0
Reputation: 5230
You are setting UIImage
and you are checking the backgroundImage
.
Try
if([atmbtn imageForState:UIControlStateNormal] ==
[UIImage imageNamed:@"check_box_on.png"])
instead of
if([atmbtn backgroundImageForState:UIControlStateNormal] ==
[UIImage imageNamed:@"check_box_on.png"])
Upvotes: 0
Reputation: 4527
You can simply use
[atmbtn setBackgroundImage:[UIImage imageNamed:@"check_box_off.png"]
forState:UIControlStateNormal];
[atmbtn setBackgroundImage:[UIImage imageNamed:@"check_box_on.png"]
forState:UIControlStateSelected];
Where atmbtn
is the outlet of the button in your xib.
Upvotes: 0
Reputation: 3911
use this:
[atmbtn setBackgroundImage:[UIImage imageNamed:@"check_box_on.png"] forState:UIControlStateNormal];
Upvotes: 1