how to use if else conditon on button press based on image of button?
I am trying to use some logics on the base of button click.i use button as checkmark and when i click on this check mark the image of button changed into checked.png or unchecked.png.On that basis i use this code...
if([UIImage imageNamed:@"checkbox_ticked.png"])
{
isActiveStr=[arrayPickerData objectAtIndex:17];
NSLog(@" is active value is %@ ",isActiveStr);
isActiveStr=nil;
}
else
{
NSLog(@"no vlaue send");
isActiveStr=[[NSMutableString alloc]initWithString:@"1"];
NSLog(@" is active value %@",isActiveStr);
}
Now i dont know how to use the else condtion...i run this code but it always run only if codition.It never goes in else conditon.I want that i codtion is true it goes in if part and when condition is false it goes in else part开发者_如何学Go.And how i use image property of button to check the condition.
You have to have a flag variable that holds the status of the button(checked/unchecked).
BOOL checked;
And, you have to update it when ever you click on the the button.
- (void)onButtonTapped:(UIButton *)button {
checked = !checked;
...
}
And change your if statement like this,
if (checked) {
// The button is checked
} else {
// The button is not checked
}
Try this if
statement:
if ([[myButton imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"checkbox_ticked.png"]]) {
...
But as for me this is bad approach, better to have some bool flag that indicate that button is checked.
the if condition will always evaluate true. You should instead check for [myButton state] to see if it's enabled or not. You may have to add an IBOutlet or IBAction according to your needs.
USE this in your IBAction method
if(!btnCheckbox.selected)
{
[btnCheckbox setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"check-out_h" ofType:@"png"]] forState:UIControlStateNormal];
btnCheckbox.selected=YES;
}
else {
[btnCheckbox setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"check-out" ofType:@"png"]] forState:UIControlStateNormal];
btnCheckbox.selected=NO;
}
-(void)checkBoxIsHideNationWideClicked
{
NSLog(@"nation wide button clicked");
mybtn.selected=!mybtn.selected;
defaultsCheckBox=[NSUserDefaults standardUserDefaults];
if (mybtn.selected)
{
[defaultsCheckBox setValue:@"One" forKey:@"CheckBox"];
NSLog(@" is active value is %@ is fetched succesfuly",hideNationWideStr);
[CommonVar setHideNationwideData:hideNationWideStr];
NSLog(@" is active value send to cmmon class %@ sent succesfuly",hideNationWideStr);
}
else
{
[defaultsCheckBox setValue:@"Two" forKey:@"CheckBox"];
NSLog(@"no vlaue send");
hideNationWideStr=[[NSMutableString alloc]initWithString:@"1"];
[CommonVar setHideNationwideData:hideNationWideStr];
NSLog(@" is active value send to cmmon class %@ sent succesfuly",hideNationWideStr);
}
}
精彩评论