无法将textLabel添加到UICollectionViewCell?

时间:2014-12-17 01:52:16

标签: ios swift uicollectionview uicollectionviewcell textlabel

我有一个类文件,它是UICollectionViewController类的子类。在我的cellForItemAtIndexPath方法中,我正在尝试设置单元格的textLabel。但是,完成中没有textLabel选项。到目前为止这是方法:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
    // Configure the cell
    cell.backgroundColor = cellColor ? UIColor.blueColor() : UIColor.orangeColor()
    //cell.textLabel.text = "Text"???
    switch indexPath.item {
    case 0...5:
        cellColor = true
    case 6...13:
        cellColor = false
    default:
        cellColor = true
    }
}

如何将textLabel添加到单元格?

3 个答案:

答案 0 :(得分:4)

与tableViewCell不同,UICollectionViewCell没有textLabel。您需要将UILabel添加到单元格的内容视图中 例如:

var title = UILabel(frame: CGRectMake(0, 0, cell.bounds.size.width, 40))
cell.contentView.addSubview(title)

答案 1 :(得分:0)

使用Luke的文档。它是在Xcode"帮助"菜单。

UICollectionViews没有textLabels - 这就是你没有完成的原因。

他们有contentViews。您可以将文本放在内容视图中。任何UIView子类都可以。如果你想要的 all 是文本(没有图形),那么你可以使用UITextView作为你的内容视图,然后分配给它的"文本"属性:

cell.contentView.text =" Text"

但是,您需要一个UICollectionView的子类,它已经为contentViews提供了UITextView。

答案 2 :(得分:0)

Swift 4

以下是将文本添加到集合视图单元格的Swift 4方法:

    let title = UILabel(frame: CGRect(x: 0, y: 0, width: cell.bounds.size.width, height: 40))
    title.textColor = UIColor.black
    title.text = "T"
    title.textAlignment = .center
    cell.contentView.addSubview(title)