【发布时间】:2018-12-12 06:44:37
【问题描述】:
我有一个集合视图,它在集合视图单元格内有步进器,用于增加产品的数量,如下图所示。
我需要知道,当我单击集合视图单元格上的步进器时。我怎么知道那个集合视图单元格的indexPath.item?所以我可以使用视图控制器中选择的 indexPath 修改数据?
所以如果我在第二个单元格中更改步进器,我将始终得到 indexPath.item = 1
我之前认为indexPath 将来自下面的didSelectItemAt 方法。但是当我点击集合视图单元格内的步进器时,似乎不会触发didSelectItemAt 方法。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
所以我想我可以从cellForRowAt IndexPath 获取 indexPath 并使用协议委托模式。这是我做的方法,我得到了错误的indexPath
所以如果我在第二个单元格中更改步进器,我不会总是得到 indexPath.item = 1 ,它可以是 2,3,0 等。
这是视图控制器代码:
class WishListVC: UIViewController, ListProductCellDelegate {
var products = [Product]()
var selectedProduct : Product?
// method from ListProductCellDelegate
func stepperButtonDidTapped(at selectedIndexPath: IndexPath, stepperValue: Int) {
// get selectedIndexPath
// perform some action based on selectedIndexPath
}
}
extension WishListVC : UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return products.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WishListStoryboardData.CollectionViewIdentifiers.productSliderCell.rawValue, for: indexPath) as? ListProductCell else { return UICollectionViewCell()}
cell.productData = products[indexPath.item]
cell.indexPath = indexPath // I send the indexPath to the cell.
cell.delegate = self
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedProduct = products[indexPath.item]
performSegue(withIdentifier: WishListStoryboardData.SegueIdentifiers.toProductVC.rawValue, sender: nil)
}
}
这里是集合视图单元格中的代码:
protocol ListProductCellDelegate {
func stepperButtonDidTapped( at selectedIndexPath: IndexPath, stepperValue: Int)
}
class ListProductCell: UICollectionViewCell {
var indexPath: IndexPath?
var delegate: ListProductCellDelegate?
var productData : Product? {
didSet {
updateUI()
}
}
@IBAction func stepperDidTapped(_ sender: GMStepper) {
guard let indexPath = indexPath, let collectionView = collectionView else {return}
self.delegate?.stepperButtonDidTapped(at: indexPath, stepperValue: Int(sender.value))
}
func updateUI() {
// update the UI in cell.
}
}
【问题讨论】:
-
只要加上stepper tag value = indexPath.row,在stepper tag value的基础上检查即可。
标签: ios swift uicollectionview uicollectionviewcell uistepper