2014-03-13 48 views
1

我遇到了ios7中的自定义UIButton子类的问题。我想要做的是在nib文件中添加一个按钮并在界面构建器中设置其背景颜色。在IB中,我将它的类设置为一个自定义的UIButton子类:MyShapeButton。然后,使用我的UIButton子类(MyShapeButton)中的drawRect()函数绘制一个自定义按钮形状,并用该背景色填充。我可以完成所有这些工作,但真正的问题是我无法从按钮中删除原始背景颜色,使其变得透明。所以。我的形状被绘制,但原始背景颜色模糊了它。以编程方式删除UIButton背景颜色

请注意以下几点: 我的按钮类型设置为自定义,因为其他SO帖子都说这很重要。它没有帮助。

这里是从我的子类的drawRect代码:

 
- (void)drawRect:(CGRect)rect 
{ 
    UIColor* buttonColor = self.backgroundColor; 

//========= this doesn't work ========= 
    [self setBackgroundColor:[UIColor clearColor]]; 


    CGFloat width = rect.size.width; 
    CGFloat height = rect.size.height; 
    CGFloat radius = 10; 
    // Drawing code 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextMoveToPoint(context, 0, height); //bottom left 
    CGContextAddLineToPoint(context, 0, radius); 
    CGContextAddArcToPoint(context, 0, 0, radius, 0, radius); 
    CGContextAddLineToPoint(context, width, 0); 
    CGContextAddLineToPoint(context, width, height-radius); 
    CGContextAddArcToPoint(context, width, height, width-radius, height, radius); 
    CGContextAddLineToPoint(context, 0, height); 

    //shape is drawn here, but you can't see it: 
    CGContextSetFillColorWithColor(context, buttonColor.CGColor); 

    //uncomment this to see the button shape 
    //CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor); 

    CGContextFillPath(context); 


} 

感谢您的帮助。

更新:这里是的drawRect()的工作代码:

 
- (void)drawRect:(CGRect)rect 
{ 
    CGFloat radius = 10.f; 
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds             byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight 
                 cornerRadii:CGSizeMake(radius, radius)]; 
    CAShapeLayer *maskLayer = [CAShapeLayer layer]; 
    maskLayer.frame = self.bounds; 
    maskLayer.path = maskPath.CGPath; 
    self.layer.mask = maskLayer; 
} 
+0

http://www.raywenderlich.com/36341/paintcode-tutorial-dynamic-buttons你可以在本教程 – Harsh

+0

问题看看这里不是“如何在按钮中绘制形状?”。问题是我想使用界面生成器中设置的背景颜色填充我的形状,然后删除原始背景颜色(填充矩形)。我可以在代码中手动设置颜色,但我希望它能自动使用IB背景颜色来重新绘制具有自定义形状的按钮。然后,我不必在代码中设置颜色,这很烦人。 – Andy

回答

相关问题