Muh*_*med 1 uibutton uicollectionview uicollectionviewcell swift
我有 CollectionView 有多个动态单元格,foreach 单元格有按钮,它具有添加项目数的操作,这是我的简单代码:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if ids.count == 0
{
return 3
}else
{
return ids.count
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if ids.count == 0
{
let cell = myCollection.dequeueReusableCellWithReuseIdentifier("loadingItems", forIndexPath: indexPath)
return cell
}else
{
let cell =myCollection.dequeueReusableCellWithReuseIdentifier("cellProduct", forIndexPath: indexPath) as! productsCollectionViewCell
cell.addItems.addTarget(self, action: #selector(homeViewController.addItemsNumberToCart(_:)), forControlEvents: UIControlEvents.TouchUpInside)
}
return cell
}
}
Run Code Online (Sandbox Code Playgroud)
这是添加项目的方法
func addItemsNumberToCart(sender:UIButton)
{
sender.setTitle("Added to cart", forState: UIControlState.Normal)
}
Run Code Online (Sandbox Code Playgroud)
这是我的 collectionViewCell 类
import UIKit
class productsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var addItems: UIButton!
}
Run Code Online (Sandbox Code Playgroud)
它正在工作并改变值,但它改变了多行的值,不仅仅是选定的行,现在有什么问题吗?
看起来您正在添加目标但从未删除它。因此,随着单元格被重用,按钮会累积多个目标。有几种方法可以解决这个问题;一种是prepareForReuse
在你的productsCollectionViewCell
类中实现(顺便说一句,应该有一个大写的P):
class ProductsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var addItems: UIButton!
func prepareForReuse() {
super.prepareForReuse()
addItems?.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
}
}
Run Code Online (Sandbox Code Playgroud)