如何将数字传递给手势识别器操作?

时间:2016-04-28 11:35:13

标签: ios swift uigesturerecognizer

我有下一个代码

var i = 0
for answer in answeres{ 
    let singleTap = UITapGestureRecognizer(target: self, action:#selector(tapDetected(_:))
    imageView.addGestureRecognizer(singleTap)
    i+=1
}

func tapDetected(position : Int) {
    print(position)
}

如何将var'i'传递给每个imageView,因此当用户单击imageView时,它会在日志中打印正确的数字?

1 个答案:

答案 0 :(得分:2)

识别器调用的方法作为第一个参数传递给识别器:

func tapDetected(sender: UITapGestureRecognizer) {}

这意味着您可以使用识别器的view属性来访问与其关联的视图。并且该数字可以存储为视图标记:

var i = 0
for answer in answers {
   let singleTap = …
   let imageView = …
   imageView.addGestureRecognizer(singleTap)
   imageView.tag = i
   i = i + 1
}

func tapDetected(sender: UITapGestureRecognizer) {
    print(sender.view.tag)
}