我正在尝试在 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)
}
最佳答案
UITapGestureRecognizer
的处理函数作为 sender
传递给 UITapGestureRecognizer
。您可以使用 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:")
关于swift - 如何在 Swift 中将 'addTarget' 转换为 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37630921/