sending a parameter argument to function through UITapGestureRecognizer selector

不羁的心 提交于 2019-11-30 15:38:54

问题


I am making an app with a variable amount of views all with a TapGestureRecognizer. When the view is pressed, i currently am doing this

func addView(headline: String) {
    // ...
    let theHeadline = headline
    let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
    // ....
}

but in my function "handleTap", i want to give it an additional parameter (rather than just the sender) like so

func handleTap(sender: UITapGestureRecognizer? = nil, headline: String) {
}

How do i send the specific headline (which is unique to every view) as an argument to the handleTap-function?


回答1:


Instead of creating a generic UITapGestureRecognizer, subclass it and add a property for the headline:

class MyTapGestureRecognizer: UITapGestureRecognizer {
    var headline: String?
}

Then use that instead:

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

I tried this. It worked great.



来源:https://stackoverflow.com/questions/35635595/sending-a-parameter-argument-to-function-through-uitapgesturerecognizer-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!