我正在使用TapGestureRecognizer创建一个具有可变数量视图的应用。按下视图时,我目前正在执行此操作
func addView(headline: String) {
// ...
let theHeadline = headline
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
// ....
}
但在我的功能" handleTap"中,我想给它一个额外的参数(而不仅仅是发送者),如此
func handleTap(sender: UITapGestureRecognizer? = nil, headline: String) {
}
如何将特定标题(每个视图都是唯一的)作为handleTap函数的参数发送?
答案 0 :(得分:23)
不是创建通用的UITapGestureRecognizer,而是将其子类化并为标题添加属性:
class MyTapGestureRecognizer: UITapGestureRecognizer {
var headline: String?
}
然后使用它:
override func viewDidLoad() {
super.viewDidLoad()
let gestureRecognizer = MyTapGestureRecognizer(target: self, action: "tapped:")
gestureRecognizer.headline = "Kilroy was here."
view1.addGestureRecognizer(gestureRecognizer)
}
func tapped(gestureRecognizer: MyTapGestureRecognizer) {
if let headline = gestureRecognizer.headline {
// Do fun stuff.
}
}
我试过这个。它运作得很好。