swift3.0之CollectionView添加长按手势并识别cell名称

一、在UICollectionViewDataSourced 绘制cell的代理方法中添加长按手势

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCollectionViewCell


     cell.labelCellName.text = arrayCellName[indexPath.row]

        

     ///添加长按手势///

 let longPress = UILongPressGestureRecognizer(target: self, action: #selector(cellLongPress(sender:)))

        cell.addGestureRecognizer(longPress)

        return cell

        

    }


二、在长按手势的触发方法中获取CollectionViewCell的indexPath

@objc func cellLongPress(sender:UILongPressGestureRecognizer) {

        //获取手势在collectionView中的点

        let touchPoint = sender.location(in: self.collectionView)

        var editCellName = ""

        if (sender.state == UIGestureRecognizerState.ended)

        {

            let indexPath = self.collectionView.indexPathForItem(at: touchPoint)

            if indexPath != nil {

                editCellName = arrayCellName[(indexPath?.row)!]

                

            }

        }

        

    }


猜你喜欢

转载自blog.csdn.net/amberoot/article/details/80985469
今日推荐