How to get selected IndexPath from a stepper located inside a collection view cell?

前端 未结 3 1469
刺人心
刺人心 2021-01-27 03:41

I have collection view that has stepper inside the collection view cell used to increase the number of product like the image below.

I need to know, when I clic

3条回答
  •  孤街浪徒
    2021-01-27 03:55

    In Swift a callback closure is probably the most efficient solution. It's independent of index paths, tags, view hierarchy math and protocols.

    In the cell add a callback property which passes the stepper instance. Delete both indexPath and delegate. The protocol is not needed at all.

    In the IBAction call callback and pass the stepper instance

    class ListProductCell: UICollectionViewCell {
    
        var callback: ((GMStepper) -> Void)?
    
        var productData : Product? {
            didSet {
                updateUI()
            }
        }
    
        @IBAction func stepperDidTapped(_ sender: GMStepper) {
            callback?(sender)
        }
    
    
        func updateUI() {
            // update the UI in cell.
        }
    }
    

    In the controller in cellForItemAt set the closure and handle the callback. The index path is captured in the method.

    And don't guard cells. Force unwrap it. The code must not crash. If it does it reveals a design mistake. With the guard way the table view would display nothing and you don't know why.

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WishListStoryboardData.CollectionViewIdentifiers.productSliderCell.rawValue, for: indexPath) as! ListProductCell
        cell.productData = products[indexPath.item]
        cell.callback = { stepper in 
           // handle the callback
        }
        return cell
    }
    

提交回复
热议问题