I have developed a UIView from For loop and basically it is create 3 Views from loop. and I have to add touch gesture on every View to call a method but I am unable to get current selected UIView.tag when I tap on it. it is only showing the .tag of the last view. here is my code.
    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
}
and here is the method that I am calling from every UIView touch.
@objc func ProductTapped() {
        print("",productIndex)
    }
Your code should be using delegate/callback closure, but if you want to keep using tag, try change it to:
    @objc func ProductTapped(_ sender: UITapGestureRecognizer) {
        if let view = sender.view {
            print(view.tag)
        }
    }
and the gesture attach to let producttap = UITapGestureRecognizer(target: self, action: #selector(self.ProductTapped(_:)))
productIndex does nothing here since it got overwritten on the loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With