开发者

How to make the UIButton background transparent?

I tried use a transparent png as a background, but not succes开发者_开发知识库s. How can I solve it ? thz.


Changing the Type to Custom in the Inspector window (Interface builder) worked for me.


To create a transparent button (without using an image):

- (void)viewDidLoad
{
    [super viewDidLoad];

    CALayer *layer = <your button>.layer;
    layer.backgroundColor = [[UIColor clearColor] CGColor];
    layer.borderColor = [[UIColor darkGrayColor] CGColor];
    layer.cornerRadius = 8.0f;
    layer.borderWidth = 1.0f;
}


This is a good one too:

[button.layer setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.5].CGColor];


First, add a QuartzCore framework into your project

Second, add this to header

#import <QuartzCore/QuartzCore.h>

CAGradientLayer *gradientLayer = [CAGradientLayer layer];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setFrame:CGRectMake(0, 0, 75, 37)];
[gradientLayer setFrame:aButton.frame];
[aButton.layer addSublayer:gradientLayer];

For instance, Red Gradient Button (Mixture of color)

[gradientLayer setColors:[NSArray arrayWithObjects:(id)[UIColor colorWithRed:0.841 green:0.566 blue:0.566 alpha:1.0].CGColor, (id)[UIColor colorWithRed:0.75 green:0.341 blue:0.345 alpha:1.0].CGColor, (id)[UIColor colorWithRed:0.592 green:0.0 blue:0.0 alpha:1.0].CGColor, (id)[UIColor colorWithRed:0.592 green:0.0 blue:0.0 alpha:1.0].CGColor, nil]];
[aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];


Without IB:

UIButton *b = [[UIButton buttonWithType:UIButtonTypeCustom] retain];


Change the type of the button to the custom one in IB - it has defaultly set the background to the clearColor.

If you have to have the rounded rect UIButton before it's background is transparent then i suppose changing it's background color to clearColor won't help. Then i would suggest either:

  1. Remove it from the view & replace it with other button that has the transparent background for e.g.
     UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
    [button setTitle:@"Title" forState:UIControlStateNormal];
  2. Don't use apples UIButton, subclass UIControl and draw it yourself :)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜