【发布时间】:2016-02-24 01:08:08
【问题描述】:
我有一个名为DesignableControl 的基类。我在我的自定义视图中使用它,以便我可以看到它们在情节提要中呈现。这是基类:
public class DesignableControl: UIControl {
private var view: UIView!
override public init(frame: CGRect) {
super.init(frame: frame)
configureViewForStoryboard()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureViewForStoryboard()
}
func configureViewForStoryboard() {
if let nibView = NSBundle(forClass: self.dynamicType).loadNibNamed("\(self.dynamicType)", owner: self, options: nil).first as? UIView {
view = nibView
} else {
Log("Error loading view for storyboard preview. Couldn't find view named \(self.dynamicType)")
view = UIView()
}
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
backgroundColor = .clearColor()
addSubview(view)
}
}
这是我的子类StackedButton:
class StackedButton: DesignableControl {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var label: UILabel!
...
}
上面的代码在我运行应用程序时运行并且看起来很好,但是,当我在情节提要中查看它时,它会在 DesignableControl 的下一行使用 EXC_BAD_ACCESS 使 Interface Builder 进程崩溃(为了清楚起见) :
func configureViewForStoryboard() {
let bundle = NSBundle(forClass: self.dynamicType)
print("bundle: \(bundle)")
let nibArray = bundle.loadNibNamed("\(self.dynamicType)", owner: self, options: nil)
print("nibArray: \(nibArray)") //<-- EXC_BAD_ACCESS
...
}
当我第一次编写这段代码时,它曾经可以工作,但似乎在最新版本的 Xcode(截至本文时为 7.2.1)中被破坏了。我做错了什么?
【问题讨论】:
-
看起来在 IB 中运行时,
loadNobNamed(...)返回一个 nil。愚蠢的想法,但检查self.dynamicType在两种情况下都解析为相同的名称。
标签: ios ibdesignable