xcode 创建 UICollectionViewCell 时如何在发件人中添加标签值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30927518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:20:34  来源:igfitidea点击:

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

iosiphonexcodeswiftipad

提问by user3777256

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

我对 swift 非常菜鸟,所以我有一个问题要解决我的应用程序中的问题。

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...

在 UIView 中,我刚刚添加了一个集合视图作为子视图,然后在每个单元格中我在“包装视图”中添加了一个不同的图像,所以我的问题是......

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

如何为每个单元格添加一个接收标签值的手势?例如,当我点击单元格时,它会打印 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 :)

非常感谢您的知识和帮助:)

回答by Henrique Barros

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.

将手势识别器添加到单元格时,您就拥有了它。当手势发生时,传递的参数将是单元格。因此,在声明 tapGesture 方法时,您只需访问发送者的标签属性。

func tapGesture(sender: UITapGestureRecognizer) {
    var tag = sender.view!.tag
    //do what you want
}