我有下一个代码
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时,它会在日志中打印正确的数字?
答案 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)
}