如何在Swift中将'addTarget'添加到UILabel [英] How to 'addTarget' to UILabel in Swift

查看:302
本文介绍了如何在Swift中将'addTarget'添加到UILabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift中添加标签,这些标签是循环添加的.然后,我想为每个添加一个"TapGesture"事件.它可以正常工作,但问题是调用的函数从标签中获取数据以供单击时使用,但那时标签已被重新定义,并且从最后添加的数据中获取数据,而不是从单击的数据中获取数据.如何使每个人都独一无二?

I am trying to add labels in Swift, which are added in a loop. I then want to add a 'TapGesture' event to each one as they are added. It works , but the problem is that the function called takes data from the label to use when it's clicked, but the label has been redefined by then and it takes data from the last one added, not the one that was clicked. How can I make each one unique?

self.label.attributedText = self.myMutableString
let tapGesture = UITapGestureRecognizer(target: self, action: handleTap(label))
self.label.userInteractionEnabled=true
self.label.addGestureRecognizer(tapGesture)
self.label.font = UIFont.boldSystemFontOfSize(28)
self.label.sizeToFit()
self.label.center = CGPoint(x: screenWidth, y: top)
if(kilom>=30||self.located==false){
    self.scroller.addSubview(self.label)
    if(device=="iPhone"||device=="iPhone Simulator"){
        top = top+80
    }
    else{
        top = top+140
    }
}

下面的代码是手势识别器,它获取标签数据并使用它:

The code below is the gesture recognizer that gets the label data and uses it:

func handleTap(sender:UILabel){
    var a = self.label.text
    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

    let resultViewController = storyBoard.instantiateViewControllerWithIdentifier("displayer") 

    self.presentViewController(resultViewController, animated: true, completion: nil)
}

推荐答案

UITapGestureRecognizer的处理程序函数作为sender传递给UITapGestureRecognizer.您可以使用view属性访问其所附的view.我建议像这样:

The handler function for a UITapGestureRecognizer is passed the UITapGestureRecognizer as the sender. You can access the view that it is attached to with the view property. I would suggest something like this:

func handleTap(sender: UITapGestureRecognizer) {
    guard let a = (sender.view as? UILabel)?.text else { return }

    ...
}

您还需要更改选择器的签名:

You will also need to change the signature of your selector:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))

或对于较早版本的Swift:

or for earlier versions of Swift:

let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")

这篇关于如何在Swift中将'addTarget'添加到UILabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆