Search code examples
iosimagebuttontouchcontrol-state

Set permanent button image after tap


i've programmatically created a button with an image for normalState. But I want to set a new button image when the button is pressed (the new image should be displayed for the rest of the time). I tried something, but it only works during tapping. So the button shows its old image after tapping again.

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"image1.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"image2.png"] forState:UIControlStateHighlighted];
button.frame = CGRectMake(15.0f, 32.0f, 24.0f, 20.0f);
[cell addSubview:button];

Thanks for your help.


Solution

  • Try to use this it will helps you.

      UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setBackgroundImage:[UIImage imageNamed:@"image1.png"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"image2png"] forState:UIControlStateHighlighted];
        button.frame = CGRectMake(15.0f, 32.0f, 24.0f, 20.0f);
    
        // ----------- Add this line in your code -------
        [button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:button];
    
    
        - (void)btnPressed:(UIButton *)sender
        {
              [sender setBackgroundImage:[UIImage imageNamed:@"image2.png"] forState:UIControlStateNormal];
        }