Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the UIButton state to be highlighted after pressing it

I have a typical requirement wherein I need to keep a button in highlighted state after pressing it. I need to perform a task which should work only when a button is in highlighted state. Actually I am setting a button state to highlighted programatically.

[sender setHighlighted:YES];

And once the button is in highlighted state i need to perform another action.

- (IBAction)changeState: (UIButton*)sender
{   
    if (sender.highlighted == YES)
    {
        [self performSomeAtion:sender];
    }
}

But, to my horror, whenever I press any button, the above condition is becoming true and the action is being performed repeatedly. Is there any way in which i can keep a UIButton's state to be highlighted after pressing it?

EDIT - Actually I need to perform 3 different actions for 3 different states of the button. I am already making use of selected state and normal state. Now, I need to make use of the highlighted state.

like image 553
A for Alpha Avatar asked Aug 29 '11 12:08

A for Alpha


2 Answers

[sender setSelected:YES]; 

or you can simulate this effect with two image for your UIButton (notselectedimage.png and selectedimage.png), then keep track button state with a BOOL variable like BOOL buttonCurrentStatus;. Then in .h file:

BOOL buttonCurrentStatus;

and in .m file

// connect this method with Touchupinside function
- (IBAction)changeState:(UIButton*)sender
{
    /* if we have multiple buttons, then we can
       differentiate them by tag value of button.*/
    // But note that you have to set the tag value before use this method.

  if([sender tag] == yourButtontag){

    if (buttonCurrentStatus == NO)
    {
        buttonCurrentStatus = YES;
        [butt setImage: [UIImage imageNamed:@"selectedImage.png"] forState:UIControlStateNormal];
        //[self performSomeAction:sender];
    }
    else
    {
        buttonCurrentStatus = NO;
        [butt setImage:[UIImage imageNamed:@"notSelectedImage.png"] forState:UIControlStateNormal];
        //[self performSomeAction:sender];
    }   
  }
}
like image 141
Vijay-Apple-Dev.blogspot.com Avatar answered Oct 04 '22 12:10

Vijay-Apple-Dev.blogspot.com


- (void)mybutton:(id)sender
{
    UIButton *button = (UIButton *)sender;
    button.selected = ![button isSelected]; // Important line
    if (button.selected)
    {
        NSLog(@"Selected");
        NSLog(@"%i",button.tag);
    }
    else
    {
        NSLog(@"Un Selected");
        NSLog(@"%i",button.tag);

    }
 }
like image 28
Rajesh Loganathan Avatar answered Oct 04 '22 13:10

Rajesh Loganathan