' #selector'的争论并不是指' @ objc'方法,财产, 或初始化程序
问题:当我尝试使用选择器传递参数时出现以上错误 代码段:
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(labelPressed(i: 1)))
func labelPressed(i: Int){
print(i)
}
答案 0 :(得分:2)
您无法将参数传递给类似的函数。动作 - 这只是传递发送者,在这种情况下是手势识别器。你想要做的是把手势附加到UIView
:
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(labelPressed())
func labelPressed(_ recognizer:UITapGestureRecognizer){
let viewTapped = recognizer.view
}
还有一些说明:
(1) You may only attach a single view to a recognizer.
(2) You might want to use both the `tag` property along with the `hitTest()` method to know which subview was hit. For example:
let view1 = UIView()
let view2 = UIView()
// add code to place things, probably using auto layout
view1.tag = 1
view2.tag = 2
mainView.addSubview(view1)
mainView.addSubview(view2)
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(mainViewTapped())
func mainViewTapped(_ recognizer:UITapGestureRecognizer){
// get the CGPoint of the tap
let p = recognizer.location(in: self)
let viewTapped:UIView!
// there are many (better) ways to do this, but this works
for view in self.subviews as [UIView] {
if view.layer.hitTest(p) != nil {
viewTapped = view
}
}
// if viewTapped != nil, you have your subview
}
答案 1 :(得分:0)
你应该声明这样的函数:
@objc func labelPressed(i: Int){ print(i) }
答案 2 :(得分:0)
Swift 3更新:
使用更现代的语法,您可以像这样声明您的函数:
@objc func labelTicked(withSender sender: AnyObject) {
并使用#selector:
初始化您的手势识别器UITapGestureRecognizer(target: self, action: #selector(labelTicked(withSender:)))