简体   繁体   中英

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.

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];
    }

You have to do the setting in the target of the button. Add the following code:

[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];

and set the image in that method for UIControlStateNormal :

- (void)buttonTapped:(UIButton *)sender {
    [button setBackgroundImage:[UIImage imageNamed:@"image2png"] forState:UIControlStateNormal];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM