Некорректный вывод в CollectionViewCell


#1

Всем привет, столкнулся с такой проблемой, что элементы, которые я вывожу в ячейках накладываются на уже имеющиеся. При том, что происходит это именно в скрытых элементах, то есть когда я захожу в контроллер он заполняет все как нужно, но если начать листать вверх-вниз, то постепенно будет появляться текст поверх имеющегося и происходит это в хаотичном порядке, вот весь код:

import UIKit

private let identifier = "Cell"

class AcquaintanceCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    
    let eyesArray = ["Голубой", "Карий", "Серый", "Зеленый", "Черный"]
    let hairArray = ["Брюнет", "Русый", "Рыжий", "Блонд", "Седой", "Шатен"]
    let ageArray = ["18-21", "22-27", "27-35", "35-44", "45+"]
    let hobbieArray = ["Фитнес", "Mix-Fight", "Танцы", "Плавание", "Хоккей", "Футбол", "Сон"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: identifier)

    }

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
    
        cell.contentView.backgroundColor = UIColor.blue
        
        populatingCellsWithData(cell: cell, textLabel: "Глаза:", x: 12, y: 9)
        populatingCellsWithData(cell: cell, textLabel: "Волосы:", x: 12, y: 3.1)
        populatingCellsWithData(cell: cell, textLabel: "Возраст:", x: 12, y: 1.8)
        populatingCellsWithData(cell: cell, textLabel: "Увлечение:", x: 12, y: 1.3)
        
        populatingCellsWithData(cell: cell, textLabel: randomFilling(array: eyesArray), x: 1.7, y: 9)
        populatingCellsWithData(cell: cell, textLabel: randomFilling(array: hairArray), x: 1.7, y: 3.1)
        populatingCellsWithData(cell: cell, textLabel: randomFilling(array: ageArray), x: 1.7, y: 1.8)
        populatingCellsWithData(cell: cell, textLabel: randomFilling(array: hobbieArray), x: 1.7, y: 1.3)
        
    
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = view.bounds.width / 2 - 30
        let height = width
        return CGSize(width: width, height: height);
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return .init(top: 20, left: 20, bottom: 20, right: 20)
    }
    
    func populatingCellsWithData(cell: UICollectionViewCell, textLabel: String, x: CGFloat, y: CGFloat) {
        let label = UILabel(frame: CGRect(x: cell.bounds.width / x, y: cell.bounds.height / y, width: cell.bounds.size.width, height: cell.bounds.height / 12))
        label.text = textLabel
        label.textColor = .white
        label.font = UIFont.systemFont(ofSize: cell.bounds.height / 12)
        cell.addSubview(label)
    }
    
    func randomFilling(array: [String]) -> String {
        let value = Int(arc4random_uniform(UInt32(array.count)))
        return array[value]
    }


}

#2

Вам обязательно нужно использовать CollectionView?


#3

ну вообще не принципиально конечно, но хотелось бы понять в чем проблема
а какой еще вариант есть?


#4

Лучше всего делать используя UITableView, если вам не нужно сверх возможностей, которых нет в таблице.
Просто для CollectionView нужно всегда обновлять размеры ячеек, отступы и прочее.
С таблицей проще будет.