集合视图无法从标签中获取文本

问题描述

我在一个视图控制器中创建了两个集合视图。出于未知原因,我无法从UILabel获取文本以进行第二个集合视图。

我创建了两个自定义单元,并将标签放置在情节提要中。

我的代码

class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate  {

    @IBOutlet weak var mainNumbers: UICollectionView!
    @IBOutlet weak var horizontalNumbers: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        mainNumbers.delegate = self
        mainNumbers.dataSource = self

        horizontalNumbers.delegate = self
        horizontalNumbers.dataSource = self
    }

    func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        if collectionView == mainNumbers {
           return 81
        } else {
           return 5
        }
    }

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

        if collectionView == mainNumbers {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",for: indexPath) as! MainCell
            cell.label.text = "f"
            cell.backgroundColor = .systemGreen
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell2",for: indexPath) as! CellSecond
            cell.cellSecond.text = "fds"
            cell.backgroundColor = .systemGreen
            return cell
        }



    }

}

对于第二个集合视图标签不显示任何内容。我不知道为什么。

class MainCell: UICollectionViewCell {
    
    @IBOutlet weak var label: UILabel!
}

class CellSecond: UICollectionViewCell {
    
    @IBOutlet weak var cellSecond: UILabel!
}

enter image description here

解决方法

第一件事:无需创建两个不同的类。像这样创建一个:

class MyCollectionViewCell: UICollectionViewCell {
let label: UILabel = {
       let lab = UILabel()
        lab.translatesAutoresizingMaskIntoConstraints = false
        lab.contentMode =  .scaleAspectFit
        lab.font = UIFont.systemFont(ofSize: 15)
        lab.clipsToBounds = true
        lab.numberOfLines = 3
        
        return lab
    }()

        override init(frame: CGRect) {
            super.init(frame: .zero)
            
            contentView.addSubview(label)

            label.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
            label.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
            label.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
            label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
   }
}

现在像您一样注册两个单元格,但是将它们分别分配给MyCollectionViewCell并调用cell.label.text = "whateverYouWant"