ios - 意外发现 UIView 类型的 @IBOutlet 为 nil
问题描述
我试图使用 xib 文件在另一个视图中创建一个集合视图,如本文中所述
根据他们提供的代码,按照那里的指导完成所有事情(或不做?):
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)
。检查并连接链接。
解决方案
推荐阅读
- mysql - 如何删除mysql中的数据库?
- google-apps-script - 在 Google App Script 中,当数据包含逗号时,如何将行附加到新工作表?
- r - R 替代函数将 c() 连接到方程中
- mongodb - mongodb填充平面文件结果?
- java - 如何获取在 android(Java) 的 textview 中添加的 SpannableStrings 列表?
- python-3.x - 从 scipy dendrogram 生成的每个簇中恢复元素
- python - 使用 Numpy 在 Python 中进行二次编程?
- mysql - MySqlDbType tiny(4) 不存在
- json - Unity中的Brick Breaker w json数据输入
- python-3.x - 如何在 QGIS 导出(pyqgis)中禁用抗锯齿