I am new to Swift and iOS. I am creating a UICollectionView programmatically and every thing is working fine but due to the dequeuing of the cell the labels in the cells are overlapping when I scroll the collection-View. How should I solve this ?
Here is the pic after scrolling some times from left to right
Here is my code:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 12;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath);
cell.backgroundColor = .red;
let label = UILabel();
label.textAlignment = .center
label.text = "(indexPath.row)";
cell.contentView.addSubview(label);
label.translatesAutoresizingMaskIntoConstraints = false;
label.leftAnchor.constraint(equalTo: cell.leftAnchor).isActive = true;
label.rightAnchor.constraint(equalTo: cell.rightAnchor).isActive = true;
label.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true;
label.bottomAnchor.constraint(equalTo: cell.bottomAnchor).isActive = true;
return cell;
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("(indexPath) wit text: (data[indexPath.row])");
}
and viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad();
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal;
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout);
collectionView.register(CollectionCell.self, forCellWithReuseIdentifier: "cell")
collectionView.delegate = self;
collectionView.dataSource = self;
collectionView.backgroundColor = .green
view.addSubview(collectionView);
collectionView.translatesAutoresizingMaskIntoConstraints = false;
collectionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true;
collectionView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true;
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -60).isActive = true;
collectionView.heightAnchor.constraint(equalToConstant: 100).isActive = true;
}
question from:
https://stackoverflow.com/questions/65651588/uicollectionviewcell-issue-with-label 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…