ios - UITapGestureRecognizer 不在 UILabel 上工作,但在父视图上工作
问题描述
视图层次结构是这样的,
- control (UIView)
- container (UIView)
- icon (UILabel)
- label(UILabel)
如果我尝试在控件上添加 Tap 手势,它会完美运行。如果我尝试在任何其他项目上添加Tap 手势,它就不起作用。
isUserInteractionEnabled
为每个元素启用。我还要求BringToFront
每个元素。
我也尝试设置UIGestureRecognizerDelegate
和检测Touch
事件,它也没有检测到。
任何想法?
这是代码,
func setGesture() {
// self.isUserInteractionEnabled = true
// containerView.isUserInteractionEnabled = true
label.isUserInteractionEnabled = true
// exclamationMark.isUserInteractionEnabled = true
self.bringSubview(toFront: containerView)
containerView.bringSubview(toFront: exclamationMark)
label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapSavingLabel)))
//exclamationMark.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapExclamationMarkButton)))
//self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selfTapped)))
}
@objc func didTapExclamationMarkButton() {
delegate?.didTapExclamationMarkButton()
}
@objc func didTapSavingLabel() {
delegate?.didTapSavingLabel()
}
@objc func selfTapped() {
print("Self Tapped")
}
如果我取消注释 Self 上的 Tap 手势,效果很好。
解决方案
问题是标签的一个或多个超级视图的帧大小为0,0
. 当该视图的.clipsToBounds
属性为false
时,它允许在屏幕上看到其子视图(在本例中为标签),但它会超出其父视图的范围。
这种情况下的任何视图都不会响应触摸/手势。
解决布局问题并正确设置框架后,添加到标签的点击手势将按预期工作。
推荐阅读
- python-3.x - Python Requests delete() 方法出现 401 客户端错误
- twilio - 自动驾驶仪和小数截断
- ibm-data-replication - 支持的表类型:DB2 LUW 的复制引擎
- sql - 获取一段时间内的会话持续时间平均值
- python-3.x - Pandas Groupby 获取每组的平均值
- c - 在格式化的 printf 中使用 #define 来定义精度
- javascript - Cookiebot 横幅覆盖带有印记的页脚部分
- c# - OnTriggerEnter2D 发生得太慢
- ember.js - 如何对 Octane 组件进行可选操作?
- ruby-on-rails - 使用单击时的时间戳更新 Rails 索引视图中的记录