如何在Swift中将“addTarget”添加到UILabel

时间:2016-06-04 13:42:39

标签: swift uilabel addtarget

我正在尝试在Swift中添加标签,这些标签会在循环中添加。然后我想在添加时为每个添加一个'TapGesture'事件。它可以工作,但问题是被调用的函数从标签中获取数据,以便在单击时使用,但标签已经被重新定义,然后它会从最后添加的数据中获取数据,而不是单击的数据。我怎样才能使每一个都独一无二?

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

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

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)
}

2 个答案:

答案 0 :(得分:7)

UITapGestureRecognizer的处理函数作为UITapGestureRecognizer传递给sender。您可以使用view属性访问附加到的view。我会建议这样的事情:

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

    ...
}

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

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

或早期版本的Swift:

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

答案 1 :(得分:0)

SWIFT 5.1

@vacawana 给出了很好的答案,但我只想发布一个完整的代码会是什么样子来帮助一下。您需要向标签添加一个 isUserInteractionEnabled.. 以及创建的 tapGesture。

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

label.isUserInteractionEnabled = true
label.addGestureRecognizer(tapGesture)
return label

别忘了在“func handleTap”前加上@objc