[英]UIView init override causes IBDesignable to crash
我对 XCode 7.1 界面构建器有一个非常奇怪的问题。 我有一个非常简单的 UIView 子类,它在故事板编辑器中呈现良好:
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)
}
它失败并出现错误:
我 100% 确定该初始化程序覆盖使它崩溃,因为我已经复制了几次。 如果我只注释掉它,它会再次起作用。
任何人都知道为什么会发生这种情况,以及是否有办法修复/解决它?
我一整天都在为此苦苦挣扎。 您需要实施:
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...
}
我遇到了类似的问题,发现在 prepareForInterfaceBuilder() 函数之外为 ibdesignable 视图设置掩码会导致渲染崩溃……prepareForInterfaceBuilder() 不是从系统调用的,而是由 interfaceBuilder 调用的,因此您需要设置此处和awakeFromNib() 中的maskView。
我在另一个 SO 页面上找到了答案: @IBDesignable crashing agent
您需要覆盖init(frame:)
和init?(coder:)
。 如果仅覆盖两者之一,IB 渲染将崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.