Perform Segue from UICollectionViewCell Button different from Cell Click

前端 未结 3 963
旧时难觅i
旧时难觅i 2021-02-06 15:27

I have a UICollectionViewCell, with a UIButton. And I have two different actions. The first one, when the user presses the cell, it will segue to anoth

3条回答
  •  你的背包
    2021-02-06 15:55

    Here's an elegant solution that only requires a few lines of code:

    1. Create a custom UICollectionViewCell subclass
    2. Using storyboards, define an IBAction for the "Touch Up Inside" event of your button
    3. Define a closure
    4. Call the closure from the IBAction

    Swift 4+ code

    class MyCustomCell: UICollectionViewCell {
    
            static let reuseIdentifier = "MyCustomCell"
    
            @IBAction func onAddToCartPressed(_ sender: Any) {
                addButtonTapAction?()
            }
    
            var addButtonTapAction : (()->())?
        }
    

    Next, implement the logic you want to execute inside the closure in your

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MyCustomCell.reuseIdentifier, for: indexPath) as? MyCustomCell else {
                fatalError("Unexpected Index Path")
            }
    
            // Configure the cell
            // ...
    
    
            cell.addButtonTapAction = {
                // implement your logic here, e.g. call preformSegue()  
                self.performSegue(withIdentifier: "your segue", sender: self)              
            }
    
            return cell
        }
    

    You can use this approach also with table view controllers.

提交回复
热议问题