2014-03-13 46 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

回答

相關問題