触摸时获取UiView标记



我已经从For循环中开发了一个UIView,基本上就是从循环中创建3个视图。我必须在每个视图上添加触摸手势才能调用方法,但当我点击它时,我无法获得当前选定的UIView.tag。它只显示最后一个视图的.tag。这是我的密码。

for i in 0 ... 2 {
let productView = UIView()
productView.tag = i
productView.isUserInteractionEnabled = true
let producttap = UITapGestureRecognizer(target: self, action: #selector(self.ProductTapped))
productView.addGestureRecognizer(producttap)
productView.frame = CGRect(x: xOffset, y: CGFloat(buttonPadding), width: 200, height: scView1.frame.size.height)
xOffset = xOffset + CGFloat(buttonPadding) + productView.frame.size.width
scView1.addSubview(productView)
productIndex = productView.tag
}

这是我从每次UIView触摸中调用的方法。

@objc func ProductTapped() {
print("",productIndex)
}

您的代码应该使用委托/回调闭包,但如果您想继续使用标记,请尝试将其更改为:

@objc func ProductTapped(_ sender: UITapGestureRecognizer) {
if let view = sender.view {
print(view.tag)
}
}

以及手势附加到let producttap = UITapGestureRecognizer(target: self, action: #selector(self.ProductTapped(_:)))

productIndex在这里什么也不做,因为它在循环上被覆盖了

productIndex当前与您附加视图的敲击手势没有关系。你确实在循环中设置了productIndex,但这与你的手势无关。

也许你想要

let producttap = UITapGestureRecognizer(target: self, action: #selector(productTapped(_:))

@objc func productTapped(_ gesture: UITapGestureRecognizer) {
print("tag is",gesture.view.tag)
}

最新更新