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)
}
它看起来不错,当我使用它作为故事板单独的UIView。
但是,当我将它添加为我的自定义UIButton的子视图,然后在故事板中添加自定义按钮时,椭圆消失并且背景变黑。
相关的代码在这里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:我选择使用约束布局,现在我只是使用框架进行测试。所以,请不要提及有关错误。
这是正确的,但它是奇怪,为什么一个视图的默认背景颜色为黑色 – duan 2015-02-06 07:29:17
或者你也可以设置它'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
我明白了,非常感谢。 @ gabbler – duan 2015-02-06 07:41:52