gpt4 book ai didi

ios - 触摸时获取 UiView 标签

转载 作者:行者123 更新时间:2023-12-01 15:40:57 24 4
gpt4 key购买 nike

我已经从 For 循环中开发了一个 UIView,基本上它是从循环中创建 3 个 View 。并且我必须在每个 View 上添加触摸手势来调用方法,但是当我点击它时我无法获取当前选择的 UIView.tag 。它只显示最后一个 View 的 .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)
}

最佳答案

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

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

并将手势附加到 let productap = UITapGestureRecognizer(target: self, action: #selector(self.ProductTapped(_:)))

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

关于ios - 触摸时获取 UiView 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63882367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com