ios - CGContextRef 无法与 @IBDesignable 一起使用(错误 :The agent Crashed)

标签 ios swift core-graphics xcode7.1 ibdesignable

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

  1. 错误:IB Designables:无法更新自动布局状态: 代理崩溃了

  2. 错误:IB Designables:无法渲染实例 DashboardHeaderView:代理崩溃了

以下是代码示例

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()! 

我覆盖了 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()
}

所有这些在 Objective C 中运行良好,但在 swift 中崩溃

最佳答案

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

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();

关于ios - CGContextRef 无法与 @IBDesignable 一起使用(错误 :The agent Crashed),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34216879/

相关文章:

ios - 一个 uibutton 是否可以设置另一个 uibutton 的标题,因为这两个 uibutton 都是在 Storyboard 中创建的?

ios - CollectionViewLayout 补充 View 高度等于内容

ios - 使用 SiriKit 开始锻炼时,Siri 始终响应 'Continue in the app'

macos - OpenGL 纹理单元的范围是什么?

swift - 在 CALayer 上过滤,除了形状是(不一定不同的)矩形的并集

ios - 为什么这个堆栈 View 不能在 Playground 上工作?

ios - 调频数据库队列错误 : database is locked

iOS:通过以编程方式添加约束作为唯一指示器获取 View 高度

objective-c - 我无法调用 swift 文件中的方法

ios - 用核心图形绘制一个羽毛状的圆圈