Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add tag value in sender while creating an UICollectionViewCell?

I'm very noob with swift, so i Have a question for solve a trouble in my app.

In a UIView i have just added a Collection View as a Sub View, then in each cell I added a different IMAGE inside a "Wrapper View", so my question is...

How can i add a gesture that receives the tag value by a sender for each cell? For example, when i tap the cell it'll print the indexPath

I have this code:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{


    var cell:UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as! UICollectionViewCell;

    cell.backgroundColor = UIColor.blueColor().colorWithAlphaComponent(0);

    //Agregamos imagen a la celda
    var imageView = UIImageView(frame: CGRectMake(0, 0, cell.frame.width - 0, cell.frame.height - 0))
    var image = UIImage(named: "car_aguas_gerber_7.png")
    imageView.image = image
    cell.backgroundView = UIView()
    cell.backgroundView!.addSubview(imageView)



    // Sección donde creamos el TAP para cada imageView

    // Creamos el tap gesture recognizer
    let tapGesture = UITapGestureRecognizer(target: self, action: "tapGesture:")

    // Se lo adjudicamos al image view previo
    cell.addGestureRecognizer(tapGesture)

    // Nos aseguramos que tenga interacción hacia el usuario
    cell.userInteractionEnabled = true


    cell.tag = indexPath.row;
    println(cell.tag);


    //Una vez creada la celda la regresamos completa.
    return cell;


}

Thanks a lot in advance for your knowledge and help :)

like image 915
user3777256 Avatar asked Jun 18 '15 23:06

user3777256


1 Answers

You just have it when adding the gesture recognizer to the cell. When the gesture happens, the parameter passed will be the cell. So when declaring the tapGesture method you just access the sender's tag property.

func tapGesture(sender: UITapGestureRecognizer) {
    var tag = sender.view!.tag
    //do what you want
}
like image 159
Henrique Barros Avatar answered Oct 13 '22 08:10

Henrique Barros