我在UICollectionViewCell中有2个UIButton,当按下添加按钮时,商品价格会添加到totalPrice中,并且该按钮变为隐藏状态,而Remove按钮变为活动状态。当按下“删除”按钮时,我希望从totalPrice中删除该商品的价格,并隐藏“删除”按钮,并使“添加”按钮处于活动状态。它用于在结帐流程中添加和删除项目。现在,价格会减去并加到totalPrice上,但是在按下Remove之后,该按钮仍然显示在屏幕上。因此,多次按会导致totalPrice为负数。
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
var totalPrice = Double()
private var hiddenRows = Set<Int>()
@objc func addPressed(_ sender : UIButton){
hiddenRows.insert(sender.tag)
let item = itemsArr[sender.tag].price
totalPrice += Double(item) ?? 0
sender.isHidden = true
collectionView?.reloadData()
print(item)
print(totalPrice)
}
@objc func buttonTapped(cell: PostCell) {
cell.myButton.isHidden = false
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
let item = itemsArr[indexPath.row]
cell.delegate = self
cell.set(name: item.name, brand: item.brand, price: item.price)
cell.myButton.tag = indexPath.row
cell.removeButton.addTarget(self, action: #selector(buttonTapped(cell:)), for: .touchUpInside)
print(item)
return cell
}
protocol PostCellDelegate {
func buttonTapped(cell: PostCell)
}
class PostCell: UICollectionViewCell {
var delegate: PostCellDelegate?
let myButton: UIButton = {
let button = UIButton(type: .system)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
button.setTitle("Add", for: .normal)
button.backgroundColor = .red
// button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) //here....
return button
}()
let removeButton: UIButton = {
let button = UIButton(type: .system)
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.setTitle("Remove", for: .normal)
return button
}()
override func prepareForReuse() {
super.prepareForReuse()
self.delegate = nil
}
func set(name: String, brand: String, price: String){
nameLabel.text = name
brandLabel.text = brand
priceLabel.text = price
}
override init(frame: CGRect) {
// self.delegate = nil
super.init(frame: frame)
self.contentView.addSubview(containerView)
containerView.addSubview(nameLabel)
containerView.addSubview(brandLabel)
containerView.addSubview(priceLabel)
containerView.addSubview(myButton)
containerView.addSubview(removeButton)
containerView.addSubview(finalLabel)
setupCellConstraints()
}
func someButtonTapped(sender: UIButton){
self.delegate?.buttonTapped(cell: self)
}
答案 0 :(得分:0)
仅在可重用单元格中设置对象的isHidden
属性不是一个好主意。您还需要更新dataSource(Array)以匹配表视图中的单元格。在这种情况下,您可以在isAdded
模型中添加item
属性,并在触摸按钮时更新其值。并在cellForRowAt中设置
cell.myButton.isHidden = !item.isAdded
cell.removeButton.isHidden = item.isAdded
通过这种方式,当调用reloadData时,tableView将基于您的数据源(即数组)进行更新。
额外: 模型属性建议
struct Item {
let name: String
let brand: String
let price: Double
var isAdded: Bool = false
}
注意:第一次回答非常抱歉,因为解释不够清楚。 xD