【问题标题】:Can't add textLabel to a UICollectionViewCell?无法将 textLabel 添加到 UICollectionViewCell?
【发布时间】:2014-12-17 01:52:15
【问题描述】:

我有一个类文件,它是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 添加到单元格中?

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewcell textlabel


    【解决方案1】:

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

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

    【讨论】:

    • 看起来像objective c,我没用过。你能把它转换成swift吗?
    • 对不起,如果我让你紧张了——有什么办法可以使文本更大,水平居中,垂直居中单元格中的标签?非常感谢。
    • 其实是很基础的东西,你真的需要了解这些基础知识。您可以使用字体属性 label.font = UIFont(name: label.font.fontName, size: 20) 使您的文本更大,您将 size 值设置得更大
    • 一种居中方式:title.center = cell.center
    • 好的,谢谢。我应该更多地研究这些字体属性。
    【解决方案2】:

    斯威夫特 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)
    

    【讨论】:

      【解决方案3】:

      使用文档,卢克。它在 Xcode 的“帮助”菜单下。

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

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

      cell.contentView.text = "文本"

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

      【讨论】:

      • UICollectionViewCell 仅有的 2 个出口是:故事板中的 backgroundViewselectedBackgroundViewcontentView 可以通过故事板分配吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多