I\'m having an issue in my cellForItemAtIndexPath where I am setting an image to my cell\'s UIButton but every time I scroll the collectionView\'s cells, it\'s placing the image
If anyone else comes across this issue (or maybe I'm the only dumb one), the problem was that I should have created my UIButton, added the subview, and constrained it inside of the cell class and from the cellForItem AtindexPath method set the image and target handler like this.
class HomeViewCell: UICollectionViewCell {
let collectionImage: UIButton = {
let image = UIButton(type: .custom)
image.contentMode = .scaleAspectFit
return image
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(collectionImage)
collectionImage.anchor(top: nil, left: nil, bottom: nil, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
collectionImage.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
collectionImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! HomeViewCell
collectionView.bounces = false
let imageNumber = indexPath.item
let image = collectionImageArray[imageNumber].withRenderingMode(.alwaysOriginal)
cell.collectionImage.setImage(image, for: .normal)
cell.collectionImage.addTarget(self, action: #selector(handleCollectionTap), for: .touchUpInside)
print(imageNumber)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height)
}
@objc func handleCollectionTap() {
let layout = UICollectionViewFlowLayout()
let cardViewer = CardViewerController(collectionViewLayout: layout)
present(cardViewer, animated: true, completion: nil)
}
Everything is running smoothly now! :)