CGContextRef无法使用@IBDesignable(错误:代理程序崩溃)

时间:2015-12-11 05:44:16

标签: ios swift core-graphics xcode7.1 ibdesignable

我正在创建一个UIButton子类来添加一些绘图。它在代码中运行良好。当我通过@IBdesignable尝试时,它给出了以下错误。

  1. 错误:IB Designables:无法更新自动布局状态: 特工坠毁

  2. 错误:IB Designables:无法呈现实例     DashboardHeaderView:代理程序崩溃

  3. 以下是代码示例

    let context:CGContextRef = UIGraphicsGetCurrentContext()!
    UIGraphicsPushContext(context)
    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0);
    
    var path:UIBezierPath!
    let pathRect:CGRect = CGRectMake(strokeWidth / 2, strokeWidth / 2, pathSize - iconStrokeWidth, pathSize - iconStrokeWidth);
    path = UIBezierPath(rect: pathRect )
    iconColor.setStroke()
    iconPath.lineWidth = iconStrokeWidth;
    iconPath.stroke()
    CGContextAddPath(context, iconPath.CGPath);
    
    let image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsPopContext();
    UIGraphicsEndImageContext();
    

    代理崩溃错误发生在

    let context:CGContextRef = UIGraphicsGetCurrentContext()! 
    

    我overirde init + drawRect + initilizeButtonDrawings但没有得到任何肯定

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.initilizeButtonDrawings()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initilizeButtonDrawings()
    }
    
    override func drawRect(rect:CGRect) {
        super.drawRect(rect)
        self.initilizeButtonDrawings()
    }
    override func prepareForInterfaceBuilder () {
        self.initilizeButtonDrawings()
    }
    

    所有这些都与目标C 完美配合,但在 swift

    中崩溃

1 个答案:

答案 0 :(得分:0)

我通过以下更新解决了这个问题......

let rect:CGRect = CGRectMake(0, 0, iconSize, iconSize)

UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0);
let context  = UIGraphicsGetCurrentContext()
 // draw icon

var iconPath:UIBezierPath!
let iconRect:CGRect = CGRectMake(iconStrokeWidth / 2, iconStrokeWidth / 2, iconSize - iconStrokeWidth, iconSize - iconStrokeWidth);
if self.iconSquare {
    iconPath = UIBezierPath(rect:iconRect )
} else {
    iconPath = UIBezierPath(ovalInRect:iconRect)
}
iconColor.setStroke()
iconPath.lineWidth = iconStrokeWidth;
iconPath.stroke()
CGContextAddPath(context, iconPath.CGPath);
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();