我正在尝试在一个单独的swift文件中创建一个自定义UIView,代码如下
import UIKit
class CustomView : UIView {
var contentView:UIView?
// other outlets
override init(frame: CGRect) { // for using CustomView in code
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) { // for using CustomView in IB
super.init(coder: aDecoder)
self.commonInit()
fatalError("NSCoding not supported")
}
private func commonInit() {
Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
guard let content = contentView else { return }
content.frame = self.bounds
content.autoresizingMask = [.flexibleHeight, .flexibleWidth]
self.addSubview(content)
}
}
然后我在一个像这样的代码的视图控制器中调用它
var custom:CustomView! = CustomView()
override func viewDidLoad() {
super.viewDidLoad()
custom.backgroundColor = UIColor.blue
view.addSubview(custom)
}
但是我得到了这样的错误:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle:
(loaded)' with name 'CustomView''
为什么我会收到此错误代码?我在youtube上看到了无处不在的谷歌,甚至还有一些类似于此的stackoverflow回答。他们都像我一样做了同样的事情,但我是唯一一个得到这个错误的人。我不知道NIB捆绑是什么。以及如何使这个自定义UIView工作