在单元格中更改按钮时出现问题. swift

px9o7tmv  于 2023-01-12  发布在  Swift
关注(0)|答案(1)|浏览(144)

我需要从UserDefaults中获取数据,并根据这些数据在单元格中显示所需的按钮。请告诉我如何完成此操作?如果在init级别插入条件,则数据为空

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
    }
    ```
ffx8fchx

ffx8fchx1#

我建议您在所有单元格中添加一个“add to cart”按钮,并将其设置为hidden。然后,在cellForItemAt方法中,选中UserDefaults并显示/隐藏该按钮。(确保始终显式地将按钮的隐藏状态设置为true或false。不要假设它已经隐藏,因为单元格可能已被回收。)

相关问题