带参数的选择器gestureRecognizer
Posted
技术标签:
【中文标题】带参数的选择器gestureRecognizer【英文标题】:selector with argument gestureRecognizer 【发布时间】:2017-05-20 04:47:57 【问题描述】:“#selector”的参数不引用“@objc”方法、属性、 或初始化器
问题:当我尝试使用选择器传递参数时出现上述错误 代码sn-p:
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(labelPressed(i: 1)))
func labelPressed(i: Int)
print(i)
【问题讨论】:
Selector to get indexPath UICollectionView Swift 3.0的可能重复 【参考方案1】:您不能将参数传递给这样的函数。动作 - 这是,只传递发送者,在这种情况下是手势识别器。您想要做的是获取您将手势附加到的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
【讨论】:
你知道如何为点击设置动画吗? Like按钮,当颜色改变时禁食。【参考方案2】:你应该像这样声明函数:
@objc func labelPressed(i: Int) print(i)
【讨论】:
这行得通吗?手势是发送者,而不是 UILabel。【参考方案3】:Swift 3 更新:
使用更现代的语法,您可以像这样声明您的函数:
@objc func labelTicked(withSender sender: AnyObject)
然后像这样初始化你的手势识别器,使用#selector:
UITapGestureRecognizer(target: self, action: #selector(labelTicked(withSender:)))
【讨论】:
以上是关于带参数的选择器gestureRecognizer的主要内容,如果未能解决你的问题,请参考以下文章