Getting UiView tag when touched

Viewed 392

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)
    }
2 Answers

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

productIndex currently has no relationship to the tap gestures that you attach your views. You do set productIndex in the the loop but that's irrelevant to your gesture.

Perhaps you want

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

and

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