I need to get data from UserDefaults and based on them display the desired button in the cell. Tell me how can this be done? If you insert a condition at the init level, then the data is empty
class ItemsCollectionViewCell: UICollectionViewCell {
static let reuseId = "ItemsCollectionViewCell"
var textItem: String = ""
var categoryItem: String = ""
var costItem: Int = 0
var imageItem: String = ""
...
let addCartButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .gray
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
button.setTitle("В корзину", for: .normal)
button.setTitleColor(.white, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.layer.cornerRadius = 12
button.addTarget(self, action: #selector(tappedAddCart), for: .touchUpInside)
return button
}()
...
class ItemsCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
...
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = dequeueReusableCell(withReuseIdentifier: ItemsCollectionViewCell.reuseId, for: indexPath) as! ItemsCollectionViewCell
cell.costItem = cells[indexPath.row].price
cell.imageItem = cells[indexPath.row].imageUrl
cell.categoryItem = "test"
cell.textItem = cells[indexPath.row].title
guard let imageUrlnew:URL = URL(string: cells[indexPath.row].imageUrl) else {
return cell
}
guard let imageData = try? Data(contentsOf: imageUrlnew) else {
return cell
}
cell.mainImageView.image = UIImage(data: imageData)
cell.nameLabel.text = cells[indexPath.row].title
cell.costLabel.text = String(cells[indexPath.row].price) " руб."
cell.nameLabel.textAlignment = .center
cell.costLabel.textAlignment = .center
return cell
}
```
CodePudding user response:
I suggest that you add an "add to cart" button to all cells, and set it to hidden. Then, in your cellForItemAt method, check UserDefaults and show/hide the button. (Make sure you always explicitly set the button's hidden state to true or false. Don't assume it is already hidden, since the cell may have been recycled.)