为不同的状态更改UIButton的渐变

时间:2011-12-13 09:51:29

标签: iphone objective-c ios uibutton cagradientlayer

最近我遇到了一个问题。我有一个UIButton和2个图像。 1表示正常状态,1表示突出显示。问题是普通状态图像是透明的,我应该用渐变来填充它。但如果我这样做,我突出显示的图像永远不会出现。这是代码的一部分:

    UIImage *balloonImage = [[UIImage imageNamed:@"balloon.png"]resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
    UIImage *balloonImageDown = [[UIImage imageNamed:@"balloon-down.png"]resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)];

    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = CGRectMake(0, 0, 320 - 45 - 10, 100);
    gradient.cornerRadius = 3.0f;
    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:221.0f/255.0f green:231.0f/255.0f blue:246.0f/255.0f alpha:1.0f]CGColor], (id)[[UIColor colorWithRed:191.0f/255.0f green:207.0f/255.0f blue:234.0f/255.0f alpha:1.0f] CGColor], nil];
    self.balloonButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.balloonButton.layer insertSublayer:gradient atIndex:0];
    [self.balloonButton setBackgroundImage:balloonImage forState:UIControlStateNormal];
    [self.balloonButton setBackgroundImage:balloonImageDown forState:UIControlStateHighlighted];
    self.theImageView = [[[UIImageView alloc]init]autorelease];
    [self.balloonButton addSubview:theImageView];
    [self.contentView addSubview:balloonButton];

渐变看起来应该如此,一切正常。如果按下按钮,则更改图像除外。

有没有办法将balloonImageDown放在渐变之前?或者我该怎么做?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

[yourButton setTitleColor:[UIColor colorWithRed:0.3 green:0.6 blue:0.9 alpha:0.5]
//                                set 'alpha' to something less than 1. -----^^^

这是为了让它变得透明。(更改alpha值) 您应该在触地和修饰方法中更改这些值。

相关问题