Andrey Chernukha
Andrey Chernukha

Reputation: 21808

UIButton changes image created in code when in highlighted state

I have two buttons. They both have the same image except the fact that one of the images is flipped. I don't want to have an excess image in the bundle of my app if it's possible to create image programmatically so i create my buttons like this:

UIImage *forwardImage = [UIImage imageNamed:rewind_btn_img];
UIImage *rewindImage  = [UIImage imageWithCGImage:forwardImage.CGImage
                                            scale:forwardImage.scale
                                      orientation:UIImageOrientationUpMirrored];

NSArray *images = @[rewindImage, forwardImage];

for (int i = 0; i < 2; i++)
{
    UIButton *btn   = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage  *image = images[i];
    btn.frame       = CGRectMake(0.f, 0.f, image.size.width, image.size.height);
    btn.center      = CGPointMake(self.playButton.center.x + (i == 0 ? - 80.f : 80.f) * TGScaleMultiplier, self.playButton.center.y);
    btn.tag         = i + 1;
    [btn setBackgroundImage:image forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(rewindButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

The problem is that when i press the button whose image is rewindImage it shows the original image, flipped to the other side. Am i doing something incorrectly here? Is there any workaround?

Upvotes: 2

Views: 116

Answers (2)

AtomRiot
AtomRiot

Reputation: 1879

if it initially looks right, but changes when you press it, Try setting the image for all button states, or at least for the normal state and the selected state.

[btn setBackgroundImage:image forState:UIControlStateNormal];
[btn setBackgroundImage:image forState:UIControlStateSelected];

you could also try setting the showsTouchWhenHighlited but the first way should work

[btn setShowsTouchWhenHighlighted:NO];

EDIT: try also setting the highlighted state, this works for me

[btn setBackgroundImage:image forState:UIControlStateHighlighted];

Upvotes: 0

ScottWasserman
ScottWasserman

Reputation: 1715

Not sure exactly why that UIImage:imageWithCGImage is flaky but I tried another method for mirroring the image and when applied to the button it works great. So get rid of the UIImage:imageWithCGImage line and use this:

UIImage *rewindImageBase = [UIImage imageNamed:rewind_btn_img];
UIGraphicsBeginImageContext(rewindImageBase.size);
CGContextRef current_context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(current_context, rewindImageBase.size.width, 0);
CGContextScaleCTM(current_context, -1.0, 1.0);
[rewindImageBase drawInRect:CGRectMake(0, 0, rewindImageBase.size.width, rewindImageBase.size.height)];
UIImage *rewindImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

That should do it.

Upvotes: 2

Related Questions