我一直在尝试使用以下代码设置我的自定义 Collection View 单元格 UILabel 文本:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: AlbumCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! AlbumCollectionViewCell
//set label text
cell.albumLabel?.text = self.objects[indexPath.item]
cell.backgroundColor = UIColor(r: 51, b: 51, g: 51)
return cell
}
但这会导致我的单元格上出现空标签。我的单元格标签返回 nil,但我的 xib 和 collectionviewcell 子类之间的所有内容看起来都是相关的。
以下是 xib 代码文件连接:
和自定义单元格类:
import UIKit
class AlbumCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var albumImage: UIImageView!
@IBOutlet weak var albumLabel: UILabel?
}
最佳答案
检查collectionView的delegate和dataSource协议(protocol)是否连接? 如果没有,则在 viewDidLoad() 方法中添加此代码
collectionView.delegate = self
collectionView.dataSource = self
关于ios - 在 ViewControllers cellForItemAt indexPath 方法中设置自定义 CollectionViewCells 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51276340/