【问题标题】:Text not being set in UILabel (or UITextField) in a UICollectionViewCell未在 UICollectionViewCell 中的 UILabel(或 UITextField)中设置文本
【发布时间】:2017-02-05 14:29:36
【问题描述】:

我做的事情太愚蠢了,我自己看不到,所以希望同行评审会有所帮助。

我有最简单的 UICollectionViewController 设置。我有一个包含 UILabel 的自定义 UIViewControllerCell。

填充 UICollectionViewController 的数据只是一个静态数组。

当我运行应用程序时,会显示 UICollectionViewController,但只显示默认标签文本,例如'标签'。

所以我认为大部分代码是正确的,只是我无法在 UILabel 中设置文本。

我敢肯定它很明显,但我就是看不到它

这里是一些代码

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! WrappedCollectionViewCell

        // Configure the cell
        var myLabel = UILabel()
        cell.brandText = myLabel
        var labelString:String =  brandList[indexPath.row]
        cell.brandText.text = labelString

        return cell
    }

所有数据都正确我可以看到正确的文本和正确的 indexPath。但是,如果我在方法结束时在 Xcode 中进行调试,我可以看到它仍然将文本显示为“标签”

这是我的自定义 UICollectionViewController。我所做的只是设置了插座。

import UIKit

class WrappedCollectionViewCell: UICollectionViewCell {

    // Previously wrong because this was set to be a UITextField
    @IBOutlet weak var brandText: UILabel!
}

所以请帮忙,我已经花了好几个小时了,这让我发疯了!

【问题讨论】:

    标签: ios swift3 uicollectionview


    【解决方案1】:

    您正在声明 UILabel 的新对象不需要这两行(您犯了一个错误,因为您在单元格类中连接了文本字段而不是标签):

    var myLabel = UILabel()
    cell.brandText = myLabel 
    

    首先,您需要将适当的 ui 组件连接到您的单元(@IBOutlet weak var brandText: UILabel),然后 只需在单元格中设置标签的文本,如下所示:

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! WrappedCollectionViewCell
    
        // Configure the cell
    
        var labelString:String =  brandList[indexPath.row]
        cell.brandText.text = labelString
    
        return cell
    }
    

    你应该很高兴!

    【讨论】:

    • Cheers K. Michal UITextField 只是问题中的一个错误。我已经修复了它。问题是你说我分配了一个新的 UILabel。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多