2015-02-06 38 views
0

我想用'添加'表面和UIBlurEffect背景來繪製一個自定義的UIButton。我覆蓋面視圖drawRect方法:子視圖添加但失去了繪圖的一部分?

class SurfaceAdd: UIView { 
    override func drawRect(rect: CGRect) { 
    var currentContext = UIGraphicsGetCurrentContext() 
    CGContextSaveGState(currentContext) 
    //draw circle 
    CGContextAddEllipseInRect(currentContext, self.bounds) 
    CGContextSetRGBFillColor(currentContext, 0, 0, 0, 0.2) 
    CGContextFillPath(currentContext) 

    CGContextRestoreGState(currentContext) 
    CGContextSetLineCap(currentContext, kCGLineCapRound) 
    CGContextSetLineWidth(currentContext, 8) 
    CGContextSetRGBStrokeColor(currentContext, 1, 1, 1, 1) 
    let height = self.frame.size.height 
    let width = self.frame.size.width 
    //draw + 
    CGContextSetShadow(currentContext, CGSizeMake(1, 1), 0) 
    CGContextMoveToPoint(currentContext, width*0.25, height/2) 
    CGContextAddLineToPoint(currentContext, width*0.75, height/2) 
    CGContextMoveToPoint(currentContext, width/2, height*0.25) 
    CGContextAddLineToPoint(currentContext, width/2, height*0.75) 
    CGContextStrokePath(currentContext) 
} 

enter image description here

它看起來不錯,當我使用它作爲故事板單獨的UIView。
但是,當我將它添加爲我的自定義UIButton的子視圖,然後在故事板中添加自定義按鈕時,橢圓消失並且背景變黑。

enter image description here

相關的代碼在這裏CustomButton

var iconAdd:SurfaceAdd! 
override init() { 
    super.init() 
    setup() 
} 

required init(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
    setup() 
} 
private func setup(){ 
    self.iconAdd = SurfaceAdd(frame: self.bounds) 
    self.addSubview(iconAdd) 
    self.setNeedsDisplay() 
} 

這有什麼錯嗎?

ps:我選擇使用約束佈局,現在我只是使用框架進行測試。所以,請不要提及有關錯誤。

回答

0

在添加到另一個視圖之前,您應該將其背景色設置爲清晰的顏色,否則,它將看起來像是黑色背景色。

self.iconAdd.backgroundColor = UIColor.clearColor() 
+0

這是正確的,但它是奇怪,爲什麼一個視圖的默認背景顏色爲黑色 – duan 2015-02-06 07:29:17

+0

或者你也可以設置它'opaque'爲false,默認是YES。不透明的視圖必須填滿它們的整個範圍或結果未定義。 drawRect:中的活動CGContext不會被清除,並且可能有非零像素,請參閱更多[here](http://stackoverflow.com/questions/8711499/ios-subview-displayed-as-a-black-rectangle如果覆蓋/ 8711523#8711523) – gabbler 2015-02-06 07:38:13

+0

我明白了,非常感謝。 @ gabbler – duan 2015-02-06 07:41:52