我的 Collection View 在 Collection View 单元格内有步进器,用于增加产品数量,如下图所示。
我需要知道,当我单击 Collection View 单元格上的步进器时。我如何知道该 Collection View 单元格的 indexPath.item
?这样我就可以使用 View Controller 中选定的 indexPath 修改数据?
所以如果我更改第二个单元格中的步进器,我将始终获得 indexPath.item = 1
我之前认为 indexPath
将来自下面的 didSelectItemAt
方法。但是当我点击 Collection View 单元格内的步进器时,didSelectItemAt
方法似乎不会被触发。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
所以我认为我可以从 cellForRowAt IndexPath
获取 indexPath 并使用协议(protocol)委托(delegate)模式。这是我做的方法,我得到了错误的indexPath
因此,如果我更改第二个单元格中的步进器,我不会总是得到 indexPath.item = 1 ,它可以是 2,3,0 等。
这是 View Controller 代码:
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)
}
}
这是 Collection View 单元格中的代码:
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.
}
}
最佳答案
您可以尝试将 tag
属性添加到步进器。因此,当您单击步进器时,您可以监听其选择器并确定调用了哪个步进器。标签值应与项目索引相同。
像这样
cell.stepper.tag = indexPath.row
以上代码应该放在 cellForRowAt 委托(delegate)函数中。
然后当用户点击步进器时调用函数并检查标签值
像这样
func stepperClicked(sender) {
//check sender.tag value
//Do something here with the tag value
}
关于ios - 如何从位于 Collection View 单元格内的步进器获取选定的 IndexPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53737450/