为什么向 UICollectionViewCell 中的按钮添加操作效果不佳?
Why adding action to button in UICollectionViewCell not working well?
我有 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
}
}
这是添加项目的方法
func addItemsNumberToCart(sender:UIButton)
{
sender.setTitle("Added to cart", forState: UIControlState.Normal)
}
这是我的 collectionViewCell class
import UIKit
class productsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var addItems: UIButton!
}
它正在工作并改变值,但它改变了多行的值,而不仅仅是选定的行,现在有人出了什么问题吗?
看起来您正在添加目标但从未删除它。因此,随着单元格的重复使用,按钮会累积多个目标。有几种方法可以解决这个问题;一种是在 productsCollectionViewCell
class 中实现 prepareForReuse
(顺便说一句,P 应该是大写的):
class ProductsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var addItems: UIButton!
func prepareForReuse() {
super.prepareForReuse()
addItems?.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
}
}
我有 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
}
}
这是添加项目的方法
func addItemsNumberToCart(sender:UIButton)
{
sender.setTitle("Added to cart", forState: UIControlState.Normal)
}
这是我的 collectionViewCell class
import UIKit
class productsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var addItems: UIButton!
}
它正在工作并改变值,但它改变了多行的值,而不仅仅是选定的行,现在有人出了什么问题吗?
看起来您正在添加目标但从未删除它。因此,随着单元格的重复使用,按钮会累积多个目标。有几种方法可以解决这个问题;一种是在 productsCollectionViewCell
class 中实现 prepareForReuse
(顺便说一句,P 应该是大写的):
class ProductsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var addItems: UIButton!
func prepareForReuse() {
super.prepareForReuse()
addItems?.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
}
}