2015-11-06 69 views
3

我有一个XCode 7.1界面生成器很奇怪的问题。我有一个非常简单的UIView子类,这使得在故事板编辑罚款:UIView初始化覆盖导致IBDesignable崩溃

import UIKit 

@IBDesignable 
class DashboardHeaderView: UIView { 

    @IBInspectable 
    var maskClipHeight: CGFloat = 40.0 

    override func layoutSubviews() { 
     super.layoutSubviews() 
     self.setMask() 
    } 

    private func setMask() { 
     let mask = CAShapeLayer() 
     mask.path = self.createMaskPath() 
     self.layer.mask = mask 
    } 

    private func createMaskPath() -> CGPath { 
     let maskPath = UIBezierPath() 
     maskPath.moveToPoint(CGPoint(x: bounds.minX, y: bounds.minY)) 
     maskPath.addLineToPoint(CGPoint(x: bounds.maxX, y: bounds.minY)) 
     maskPath.addLineToPoint(CGPoint(x: bounds.maxX, y: bounds.maxY - self.maskClipHeight)) 
     maskPath.addLineToPoint(CGPoint(x: bounds.minX, y: bounds.maxY)) 
     maskPath.closePath() 

     return maskPath.CGPath 
    } 

} 

但是,如果我只添加初始化覆盖到它:

required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
} 

它失败,错误:

  • 错误:IB Designables:无法更新自动布局状态:代理程序崩溃
  • er ror:IB Designables:无法呈现DashboardHeaderView的实例:代理程序崩溃

我100%确定初始化器重写使它崩溃,因为我已经重现了它几次。如果我只评论它,它会再次运作。

任何人都有任何想法,为什么发生这种情况,如果有办法修复/解决方法呢?

+0

您是否尝试过使用'init()'而不使用参数? – Losiowaty

+0

@Losiowaty UIView根本没有定义'init()',据我所知。而且,如果我理解的很好,界面构建器会使用init和编码器来初始化View。 –

回答

0

我有过类似的问题,发现在prepareForInterfaceBuilder()函数之外为ibdesignable视图设置掩码会导致呈现崩溃... prepareForInterfaceBuilder()不是由系统调用,只能由interfaceBuilder调用,所以你将需要在这里和awakeFromNib()中设置maskView。

1

我一直在为这一整天奋斗。你需要执行;

override init(frame: frame) 
{ 
    super.init(frame: frame); 
} 

这是IBDesignable代理程序用于实例化类的初始化过程。所以,在我的情况下,我也有另一个初始化器;

init(frame: CGRect, maxValue: Double, minValue: Double) 
{ 
    super.init(frame: frame) 

    self.maxValue = maxValue 
    self.minValue = minValue 
} 

我的init阻塞了IBDesignable需要的init。一旦我重写了上面的默认init,我可以选择将init保持原样或将其转换为便捷的init;

convenience init(frame: CGRect, maxValue: Double, minValue: Double) 
{ 
    self.init(frame: frame) 

    self.maxValue = maxValue 
    self.minValue = minValue 
} 

现在我可以为IBDesigner添加一些默认行为;

var initForIB = false; 

init(frame: CGRect, maxValue: Double, minValue: Double) 
{ 
    super.init(frame: frame) 

    self.maxValue = maxValue 
    self.minValue = minValue 
    initForIB = false; 
} 

override init(frame: CGRect) 
{ 
    super.init(frame: frame); 
    initForIB = true 
} 

required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 

override func drawRect(rect: CGRect) 
{ 
    if (initForIB) 
    { 
     initIBDefaults() 
    } 
    ...do some other stuff... 
}