Search code examples
objective-cuibuttonibaction

iOS Display Different Image on Click


Using XCode, I am trying to figure out how to display a different image when someone clicks or presses down on one of my buttons before being taken to a second screen. For example, I have a contact icon on my home screen. When a user clicks the icon, it should change to a darker version on tap before going to the contact screen. Any help is appreciated.

-(IBAction) ButtonPressed :(id)sender
{
UIButton *tempButton = (UIButton *) sender;
int tag = tempButton.tag;
NSString *viewName;
switch (tag) 
{
    case 1:
        [FlurryAnalytics logEvent:@"Contact-Screen"];
        viewName = @"ContactScreen";
        if( self.appDelegate.sound)
            [Click play];
        [self.appDelegate moveToView:viewName];
        break;
}
}

Solution

  • Simple, you just have to set a different image for the buttons selected state:

    [myButton setImage:[UIImage imageNamed:@"mySelectedImage"] forState:UIControlStateSelected];
    

    Or in interface builder:

    enter image description here

    Additional UIControlState's include:

    enum {
       UIControlStateNormal               = 0,
       UIControlStateHighlighted          = 1 << 0,
       UIControlStateDisabled             = 1 << 1,
       UIControlStateSelected             = 1 << 2,
       UIControlStateApplication          = 0x00FF0000,
       UIControlStateReserved             = 0xFF000000
    };
    

    The state of a control; a control can have more than one state at a time. States are recognized differently depending on the control. For example, a UIButton instance may be configured (using the setImage:forState: method) to display one image when it is in its normal state and a different image when it is highlighted.