fkkcloud
fkkcloud

Reputation: 167

UIButton's image with states

I have UIButton and set its background image with proper code.

`[button setImage:self.image forState:UIControlStateNormal]`

and it shows the correct image when the button is initialized but I want to make the image gone when the state is UIControlStateSelected.

I was able to change the image when it's selected but do not know which is the right function or value to be set to no image when selected.

Should I make the image alpha to be 0.0?

Thank you!

Upvotes: 0

Views: 241

Answers (4)

Adam Evans
Adam Evans

Reputation: 2097

Try [button setImage:nil forState:UIControlStateSelected];

Hope this helps!

Upvotes: 1

LE SANG
LE SANG

Reputation: 11005

Using photoshop, create new image with transparent background. Save it as nope.png file, drag it to your project. then

[button setImage:[UIImage imageNamed:@"nope.png"] forState:UIControlStateSelected];

Another way is you need to create new image category :

@interface UIImage (UIImageFrameColor)
+(UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size;
@end

@implementation UIImage (UIImageFrameColor)
+(UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size
{
    UIGraphicsBeginImageContextWithOptions(size, YES, 0);

    [color set];
    UIBezierPath * path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, size.width, size.height)];
    [path fill];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext ();
    UIGraphicsEndImageContext();

    return image;
}
@end

Then you need to make a image have same color of background color of button supper view

    UIImage *bgImage = [UIImage imageWithColor:button.supperview.backgroundColor andSize:button.frame.size];
    [button setImage:bgImage forState:UIControlStateSelected];

Upvotes: 4

Nishith Shah
Nishith Shah

Reputation: 523

Please check and try . This may be useful to you :

[button setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateHighlighted];
[button setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];

Upvotes: 1

Thanh Vũ Trần
Thanh Vũ Trần

Reputation: 790

Try [button setSeleted:YES];

if you want to create a button like check list button. This is a example code:

[button setImage:imageNormal forState:UIControlStateNormal];
[button setImage:imageSelected forState:UIControlStateSelected];
.....

-(void)btnButtonPressed:(UIButton*)sender {
    [sender setSelected:!sender.selected];
}

Hope this help you!

Upvotes: 1

Related Questions