Passing arguments to selector in Swift(在 Swift 中将参数传递给选择器)
问题描述
我正在以编程方式将 UITapGestureRecognizer 添加到我的一个视图中:
I'm programmatically adding a UITapGestureRecognizer to one of my views:
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(modelObj:myModelObj)))
self.imageView.addGestureRecognizer(gesture)
func handleTap(modelObj: Model) {
// Doing stuff with model object here
}
我遇到的第一个问题是'#selector' 的参数没有引用 '@Objc' 方法、属性或初始化程序.
The first problem I encountered was "Argument of '#selector' does not refer to an '@Objc' method, property, or initializer.
酷,所以我在 handleTap 签名中添加了@objc:
Cool, so I added @objc to the handleTap signature:
@objc func handleTap(modelObj: Model) {
// Doing stuff with model object here
}
现在我收到错误方法无法标记为@objc,因为参数的类型无法在 Objective-C 中表示.
Now I'm getting the error "Method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C.
这只是建筑物地图的图像,其中一些图钉图像指示了兴趣点的位置.当用户点击其中一个引脚时,我想知道他们点击了哪个兴趣点,并且我有一个描述这些兴趣点的模型对象.我使用此模型对象为图钉图像提供地图上的坐标,因此我认为将对象发送到手势处理程序对我来说很容易.
It's just an image of the map of a building, with some pin images indicating the location of points of interest. When the user taps one of these pins I'd like to know which point of interest they tapped, and I have a model object which describes these points of interest. I use this model object to give the pin image it's coordinates on the map so I thought it would have been easy for me to just send the object to the gesture handler.
推荐答案
看来你误解了几件事.
当使用 目标/动作,函数签名必须有一定的形式……
When using target/action, the function signature has to have a certain form…
func doSomething()
或
func doSomething(sender: Any)
或
func doSomething(sender: Any, forEvent event: UIEvent)
在哪里……
sender
参数是发送动作消息的控制对象.
The
sender
parameter is the control object sending the action message.
在您的情况下,发件人是 UITapGestureRecognizer
In your case, the sender is the UITapGestureRecognizer
另外,#selector()
应该包含 func 签名,并且不包含传递的参数.所以对于……
Also, #selector()
should contain the func signature, and does NOT include passed parameters. So for…
func handleTap(sender: UIGestureRecognizer) {
}
你应该……
let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
假设func和手势在一个视图控制器中,其中modelObj
是一个属性/ivar,不需要通过手势识别器传递,你可以在<代码>handleTap
Assuming the func and the gesture are within a view controller, of which modelObj
is a property / ivar, there's no need to pass it with the gesture recogniser, you can just refer to it in handleTap
这篇关于在 Swift 中将参数传递给选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!