突出显示时,iOS7自定义按钮变为透明

时间:2013-10-09 09:38:00

标签: iphone ios objective-c

我只是创建自己的自定义按钮,看起来像iOS6和更早的按钮,但在iOS7上,我的CustomButton在突出显示时变为透明。 我试着将属性adjustsImageWhenHighlighted设置为NO但没有任何变化,[self setAlpha:1.f]也不起作用。

以下,我的init方法:

-(void) baseInit:(CGRect)frame :(CGFloat *)colorsNormal :(CGFloat *)colorsHighlighted :(CGFloat *)colorsDisabled
{

    self.layer.borderWidth=1.0f;
    self.layer.borderColor=[[UIColor colorWithRed:0.67f green:0.67f blue:0.67f alpha:1.0f] CGColor];
    self.layer.cornerRadius=7.0f;

    self.clipsToBounds = YES;

    UIImage *image = [self generateUIImageWithGradient:frame :colorsNormal];
    [self setBackgroundImage:image forState:UIControlStateNormal];
    [self setTitleColor:[UIColor colorWithRed:0.22f green:0.33f blue:0.53f alpha:1.0f] forState:UIControlStateNormal];

    UIImage *image2 = [self generateUIImageWithGradient:frame :colorsHighlighted];
    [self setBackgroundImage:image2 forState:UIControlStateHighlighted];
    [self setTitleColor:[UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:1.0f] forState:UIControlStateHighlighted];

    UIImage *image3 = [self generateUIImageWithGradient:frame :colorsDisabled];
    [self setBackgroundImage:image3 forState:UIControlStateDisabled];
}

-(id) generateUIImageWithGradient:(CGRect)frame :(CGFloat *)colors
{
    CGSize size = CGSizeMake(frame.size.width, frame.size.height);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();

    size_t gradientNumberOfLocations = 2;
    CGFloat gradientLocations[2] = {0.0, 1.0};

    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorspace, colors, gradientLocations, gradientNumberOfLocations);

    CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(0, size.height), 0);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorspace);
    UIGraphicsEndImageContext();

    return image;
}

我的方法叫:

CGFloat colorsNormal [] = {1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f};
CGFloat colorsHighlighted [] = {0.03f,0.55f,0.97f,1.0f,0.0f,0.37f,0.90f,1.0f};
CGFloat colorsDisabled [] = {1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f};

[self baseInit:rect :colorsNormal :colorsHighlighted :colorsDisabled];

iOS6和NormalState上的魅力就像在iOS7上一样。

感谢您的帮助

1 个答案:

答案 0 :(得分:26)

将按钮类型属性设置为UIButtonTypeCustom似乎可以正常工作。问题解决了。