如何解决意外地发现UIView类型的@IBOutlet为零
我正尝试使用xib文件在另一个视图内创建一个集合视图,如此处in this article
所述按照他们提供的代码在其中完成所有操作(或不完成?)
import UIKit
@IBDesignable
class CustomView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var collectionView: UICollectionView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
let bundle = Bundle(for: type(of: self))
bundle.loadNibNamed("CustomView",owner: self,options: nil)
addSubview(contentView)
contentView.frame = bounds
contentView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
contentView.backgroundColor = .red
initCollectionView()
}
private func initCollectionView() {
let nib = UINib(nibName: "CustomCell",bundle: nil)
collectionView.register(nib,forCellWithReuseIdentifier: "CustomCell")
collectionView.dataSource = self
}
}
extension CustomView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell",for: indexPath) as? CustomCell else {
fatalError("can't dequeue CustomCell")
}
cell.label.text = "\(indexPath.item)"
return cell
}
}
但在行Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
上收到错误addSubview(contentView)
。链接已检查并连接。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。