10

我正在尝试在 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)
}
4

2 回答 2

16

UITapGestureRecognizera的处理函数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:")
于 2016-06-04T14:00:41.573 回答
4

斯威夫特 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

于 2021-02-20T20:00:30.223 回答