Search code examples
xcodeuibuttonuicontrolevents

xCode4 - How to change a UIbutton when an event changes?


I have an app, where when the button is pressed, an action happens .. I can get the button to change when the action starts by using:

UIImage *changeImage = [UIImage imageNamed:@"stopGrey.png"];
[myButton setImage:changeImage forState:UIControlStateNormal];

After the action ends, I want to be able to change the button back.. I cannot figure out how to do this..

I've tried UIControlStateDisabled/Selected/Application.. I've logged to make sure the end of action is being received.

Thanks for any help..


Solution

  • Ok, you need to do this:

    .h file:

    -(IBAction)ButtonPressed:(id)sender;
    -(IBAction)ButtonReleased:(id)sender;
    

    if you are using the graphical part join the touch down event to the method ButtonPressed and the touch up inside to ButtonReleased (right click the button for these options to appear). If you are using code to add the buttons use the method (in the viewdidload method of the .m file):

    [button addTarget:self action:@selector(ButtonPressed:) forControlEvents:UIControlEventTouchDown];
    [button addTarget:self action:@selector(ButtonReleased:) forControlEvents:UIControlEventTouchUpInside];
    

    Then you're done. The method ButtonPressed will be called every time you touch the button and the ButtonReleased method will be called every time the you let go of the button inside of it. For your question, you can add the following code to the methods (.m file)

    -(IBAction)ButtonPressed:(id)sender
    {
        [button setBackgroundImage:[UIImage imageNamed:@"ImageWhenPressed.png"] forState:UIControlStateNormal];
    }
    -(IBAction)ButtonReleased:(id)sender
    {
        [button setBackgroundImage:[UIImage imageNamed:@"ImageWhenReleased.png"] forState:UIControlStateNormal];
    }
    

    I am also guessing that you don't know how to link a button drawn in the graphical file to a pointer in the code. First you create a pointer in the .h file:

    IBOutlet UIButton *button;
    

    Then, you go to the graphical file and right click-drag the file owner image (on the left, has a orange-transparent cube as an image) to the button. Then, you select the option that has the name of the pointer. In this case, button.

    And there! you're done!