ios - 在 ViewControllers cellForItemAt indexPath 方法中设置自定义 CollectionViewCells 标签

标签 ios swift

我一直在尝试使用以下代码设置我的自定义 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 代码文件连接:

enter image description here

和自定义单元格类:

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/

相关文章:

ios - xcode9: 类 AppDelegate: UIResponder, UIApplicationDelegate...线程 1: 信号 SIGABRT

ios - 通过快速单击按钮设置选定的行

ios - 将事件添加到 iOS 7 日历

ios - 与 RestKit 的嵌套对多关系

objective-c - 如何为 objective-c 中的其他类变量赋值

ios - SKShapeNode.fillColor 不等于原始 UIColor

ios - '? :' 表达式中的结果值具有不匹配的类型 '()' 和 'Bool'

ios - 从 Storyboard加载时 XCTest 中出现 "Could not cast"错误

ios - 如何让 slider 以 0.25 为步长移动?

ios - 当我启用使用自动布局时 Xcode 5 崩溃