Swift:在 table 内单击以编程方式生成的视图
Swift: click inside programmatically generated view inside table
尝试了很多东西,但 none 成功了。
我当前的视图层次结构:
- TableView 单元格
- 垂直堆栈视图
以编程方式生成的视图 - 未触发手势识别器
let vContainer = UIView()
vContainer.translatesAutoresizingMaskIntoConstraints = false
vContainer.isUserInteractionEnabled = true
vContainer.backgroundColor = .red
//Some view generation inside box is skipped (can be seen on image)
self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
vContainer.addGestureRecognizer(tapRecognizer)
稍后 class:
@objc private func showValuePicker(sender: UITapGestureRecognizer) {
print("showValuePicker")
}
红框是View,我要添加点击的地方
将 tapRecognizer.cancelsTouchesInView = false
添加到您的代码中
self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
tapRecognizer.cancelsTouchesInView = false
vContainer.addGestureRecognizer(tapRecognizer)
为什么指定目标为 nil
?
在:
var tapRecognizer = UITapGestureRecognizer(target: nil, action: #selector(showValuePicker(sender:)))
Target
An object that is the recipient of action messages sent by the
receiver when it recognizes a gesture. nil is not a valid value.
您可以尝试添加 self
作为目标吗?
发现问题...
"self" 指向视图生成 class,与视图控制器
无关
将点击事件直接传递给视图控制器解决了问题
尝试了很多东西,但 none 成功了。
我当前的视图层次结构:
- TableView 单元格
- 垂直堆栈视图
以编程方式生成的视图 - 未触发手势识别器
let vContainer = UIView() vContainer.translatesAutoresizingMaskIntoConstraints = false vContainer.isUserInteractionEnabled = true vContainer.backgroundColor = .red //Some view generation inside box is skipped (can be seen on image) self.vsvViewContainer.addArrangedSubview(vContainer) var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:))) vContainer.addGestureRecognizer(tapRecognizer)
稍后 class:
@objc private func showValuePicker(sender: UITapGestureRecognizer) {
print("showValuePicker")
}
红框是View,我要添加点击的地方
将 tapRecognizer.cancelsTouchesInView = false
添加到您的代码中
self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
tapRecognizer.cancelsTouchesInView = false
vContainer.addGestureRecognizer(tapRecognizer)
为什么指定目标为 nil
?
在:
var tapRecognizer = UITapGestureRecognizer(target: nil, action: #selector(showValuePicker(sender:)))
Target
An object that is the recipient of action messages sent by the receiver when it recognizes a gesture. nil is not a valid value.
您可以尝试添加 self
作为目标吗?
发现问题...
"self" 指向视图生成 class,与视图控制器
无关将点击事件直接传递给视图控制器解决了问题