【发布时间】:2021-01-30 01:13:01
【问题描述】:
我正在尝试创建一个简单的集合视图。我有我的自定义单元格“SectionCell”和我的自定义类“Section”,其中包含两个@IBOutlet 属性:titleLabel 和 imageView。这两个属性都连接到它们各自的故事板视图。
在故事板中,collectionView 场景已链接到继承自 UICollectionView 的 MenuVC.swift 文件。 Cell 视图链接到 SectionCell。我已将单元格的标识符设置为“部分”。
出于调试目的,我将 view.backgroundColor 设置为黑色,并将单元格的 contentView 背景颜色设置为蓝绿色。然而,当我运行模拟器时,两者都没有显示。我得到一个白色背景,出现的只是视图标题。关于修复的任何想法?
class MenuVC: UICollectionViewController {
var sections = [Section]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Begin Learning"
view.backgroundColor = .black
}
// MARK:- CollectionView Methods
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Section", for: indexPath) as? SectionCell else {
fatalError("Unable to dequeue SectionCell ")
}
let section = sections[indexPath.item]
cell.titleLabel.text = section.title
cell.imageView.image = UIImage(named: section.image)
return cell
}
}
class SectionCell: UICollectionViewCell {
@IBOutlet var imageView: UIImageView!
@IBOutlet var titleLabel: UILabel!
}
class Section: NSObject {
var title: String
var image: String
init(title: String, image: String) {
self.title = title
self.image = image
}
}
我对在 SO 上发布问题也很陌生。如果您对如何更好地格式化问题有任何提示,我会全力以赴!
【问题讨论】:
-
检查是否正在调用
cellForItemAt- 在其中添加打印语句 -
你为场景设置了自定义类吗?
-
cellForItem 没有被调用,是的,我确实将自定义类“MenuVC”设置为 UICollectionView 场景
标签: ios swift uikit uicollectionviewcell