有什么办法可以用UITapGestureRecognizer传递参数吗?我已经看到这回答了Objective-c但是找不到快速的答案
test.userInteractionEnabled = true
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped4:"))
// Something like text.myParamater
test.addGestureRecognizer(tapRecognizer)
然后在func imageTapped4(){}下接收myParameter
一种方法是将UITapGestureRecognizer子类化,然后设置属性,我在下面发布了一个例子。您还可以检查发件人并检查是否等于某个标签,类,字符串,e.t.c
class ViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
image.userInteractionEnabled = true;
let tappy = MyTapGesture(target: self, action: #selector(self.tapped(_:)))
image.addGestureRecognizer(tappy)
tappy.title = "val"
}
func tapped(sender : MyTapGesture) {
print(sender.title)
label1.text = sender.title
}
}
class MyTapGesture: UITapGestureRecognizer {
var title = String()
}
SO上有很多例子,看看,祝你好运。
在Viewdidload中
let label = UILabel(frame: CGRect(x: 0, y: h, width: Int(self.phoneNumberView.bounds.width), height: 30))
label.textColor = primaryColor
label.numberOfLines = 0
label.font = title3Font
label.lineBreakMode = .byWordWrapping
label.attributedText = fullString
let phoneCall = MyTapGesture(target: self, action: #selector(self.openCall))
phoneCall.phoneNumber = "\(res)"
label.isUserInteractionEnabled = true
label.addGestureRecognizer(phoneCall)
功能如
@objc func openCall(sender : MyTapGesture) {
let number = sender.phoneNumber
print(number)
}
写类为
class MyTapGesture: UITapGestureRecognizer {
var phoneNumber = String()
}
通过轻击手势传递的消息大部分类似于在视图中检测到的轻击手势的位置。
假设我们在视图控制器的self.view中添加了一个轻击手势。
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.printGesPostion))
self.view.addGestureRecognizer(tapGesture)
// Do any additional setup after loading the view, typically from a nib.
}
我们可以将printGesPosition方法实现为
func printGesPostion(ges:UITapGestureRecognizer) {
print(ges.locationInView(self.view))
let subView = self.view.hitTest(ges.locationInView(self.view), withEvent: nil)
if subView?.isKindOfClass(UILabel) == true {
print( (subView as! UILabel).text! )
}
}
在这种情况下,该方法是检测轻敲手势的位置,如果它发生在UILabel
,它将打印label.text
不要忘记在ViewDidLoad或简单的故事板中设置你的label.userInteraction = true
。
最好的方法是在func qazxsw poiis触发时确定参数。您可以通过视图(查看@Developer Sheldon答案)或许多其他方式获取params。