Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting UiView tag when touched

Tags:

ios

swift

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)
    }
like image 826
Vix Hunk Avatar asked Oct 28 '25 01:10

Vix Hunk


1 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

like image 91
Tj3n Avatar answered Oct 30 '25 18:10

Tj3n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!