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

前端 未结 3 1471
刺人心
刺人心 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
    }
    
    0 讨论(0)
  • 2021-01-27 03:58

    You can try adding tag property to the stepper. So when you click on the stepper you can listen to its selector and determine which stepper was called. The tag value should be same as the item index.

    Something like this

    cell.stepper.tag = indexPath.row
    

    Above code should go inside the cellForRowAt delegate function.

    and then when user taps on the stepper call a function and check the tag value

    Something like this

    func stepperClicked(sender) {
        //check sender.tag value
        //Do something here with the tag value
    }
    
    0 讨论(0)
  • 2021-01-27 04:11

    You have the stepper because it is the sender in your action method. The stepper has a superview which is the cell (you might have to walk up more than one superview to reach the cell). Once you have the cell you can call indexPath(for:) to get the index path. Done.

    https://developer.apple.com/documentation/uikit/uicollectionview/1618094-indexpath

    0 讨论(0)
提交回复
热议问题