长按手势动作表删除单元格

时间:2018-03-13 19:44:36

标签: swift uigesturerecognizer uicollectionviewcell uiactionsheet long-press

我试图在集合视图中对单元格上的长按手势进行编码,但是我还没有发现类似的内容...我想我会在'didSelectItemAt'中编写代码。 现在只有在我点击第一个单元格时才有效... 然后我在网上找到了基于swift 3的不同解决方案。

每个人都帮帮我吗?非常感谢你!

The image show when tap long on the first cell the action sheet. But don't work when I tap to other cell...

import UIKit

    class RecipeCollViewController: UICollectionViewController, UITextFieldDelegate
    {
        struct Storyboard
        {
            static let leftAndRightPaddings: CGFloat = 2.0
            static let numberOfItemsPerRow: CGFloat = 2.0
        }

    override func viewDidLoad() {
        super.viewDidLoad()

        RecipeDataManager.shared.recipeController = self

        title = loc("TITLE_RECIPECOLL")

        navigationController?.navigationBar.prefersLargeTitles = true

        let collectionViewWidth = collectionView?.frame.width
        let itemWidth = (collectionViewWidth! -  Storyboard.leftAndRightPaddings) / Storyboard.numberOfItemsPerRow

        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: 250)
    }

    override func numberOfSections(in collectionView: UICollectionView) -> Int
    {
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return RecipeDataManager.shared.recipes.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeCell", for: indexPath) as! RecipeViewCell
        let recipe = RecipeDataManager.shared.recipes[indexPath.item]

        cell.labelNameRecipe.text = recipe.titleRecipe
        cell.imageViewRecipe.image = recipe.imageRecipe
        cell.labelPrepareTime.text = String(recipe.recipeTimeInt)
        cell.labelPeopleFor.text = recipe.peopleRecipe

        return cell
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {

    }


    // MARK: - NAVIGAZIONE
    // Metodo che scatta quando l'utente tocca una delle celle della collectionView e apre il dettaglio
    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == "RecipeDetail"
        {
            if let indexPath = self.collectionView!.indexPathsForSelectedItems?.first
            {
                let recipeDetailVC = segue.destination as! DetailRecipeViewController
                recipeDetailVC.recipe = RecipeDataManager.shared.recipes[indexPath.item]
            }
        }
    }

// MARK: - UILongPressGestureRecognizer function for the cell recipe

@IBAction func popUpActionCell(longPressGesture : UILongPressGestureRecognizer)
{
    let alertActionCell = UIAlertController(title: "Action Recipe Cell", message: "Choose an action for the selected recipe", preferredStyle: .actionSheet)

    // Configure Remove Item Action
    let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { action in

        // Delete selected Cell
        let deleteRecipe: [RecipeDataManager] = []
        if let indexPath = self.collectionView?.indexPathsForSelectedItems?.first
        {
            RecipeDataManager.shared.recipes.remove(at: indexPath.item)
            RecipeDataManager.shared.salva()
            self.collectionView?.deleteItems(at: [indexPath])
        }

        print("Cell Removed")
    })

    // Configure Cancel Action Sheet
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { acion in
        print("Cancel actionsheet")
    })

    alertActionCell.addAction(deleteAction)
    alertActionCell.addAction(cancelAction)
    self.present(alertActionCell, animated: true, completion: nil)

    self.collectionView!.reloadData()
}


}

1 个答案:

答案 0 :(得分:0)

在我的恳求下,我找到了解决问题的最终解决方案。 发布其他新开发人员需要帮助的代码!

        // MARK: - Long Press Gesture Action Sheet
    @IBAction func popUpActionCell(longPressGesture : UILongPressGestureRecognizer)
    {
        // Delete selected Cell
        let point = longPressGesture.location(in: self.collectionView)
        let indexPath = self.collectionView?.indexPathForItem(at: point)
//        let cell = self.collectionView?.cellForItem(at: indexPath!)
        if indexPath != nil
        {
            let alertActionCell = UIAlertController(title: "Action Recipe Cell", message: "Choose an action for the selected recipe", preferredStyle: .actionSheet)

            // Configure Remove Item Action
            let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { action in
                RecipeDataManager.shared.recipes.remove(at: indexPath!.row)
                print("Cell Removed")
                self.collectionView!.reloadData()
            })

            // Configure Cancel Action Sheet
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { acion in
                print("Cancel actionsheet")
            })

            alertActionCell.addAction(deleteAction)
            alertActionCell.addAction(cancelAction)
            self.present(alertActionCell, animated: true, completion: nil)

        }
    }