【发布时间】:2018-01-12 05:04:05
【问题描述】:
我创建了UIView 的子类,并通过引用 xib 文件添加到视图中。
我重写了touchesBegan 和touchesEnd 函数,以便自定义“用户按下此视图时颜色变化”的效果。
下面是这个子类:
class CustomUIView: UIView {
@IBOutlet var contentView: UIView!
override init (frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init? (coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit () {
Bundle.main.loadNibNamed("CustomUIView", owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touch begin")
super.touchesBegan(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touch ended")
super.touchesEnded(touches, with: event)
}
}
但是,touchesBegan 和 touchesEnd 永远不会被调用。
我用谷歌搜索和 stackoverflowed,已经尝试了 3 个小时,但找不到任何可行的解决方案来解决这个简单的问题....
以下是我尝试过的:
- 确保所有超级视图都启用了 UserInteraction。我什至 捕获 View Hierarchy 以检查这一点。
- 添加了touchUpInside的
IBAction,看看是否可以触发这个IBAction。答案是肯定的。 - 改为子类 UIControl 并覆盖
beginTracking。但它也没有被触发。
以下是我可以从这个 CustomView 的 ViewHierarchy 中看到的属性:
- 已启用
- 启用用户交互
- 多次触发关闭
- 阿尔法 1
- 背景
<nil color>(我也尝试将其设置为有颜色。不起作用。) - 不透明开启
- 隐藏关闭
- 清除图形上下文打开
- 剪辑到边界关闭
- 自动调整子视图大小
帮助非常感谢!
【问题讨论】:
-
什么是
contentView? -
xib 文件的根视图。但是你可以看到我还没有使用它呢
-
从您的代码中,我怀疑发送到您的自定义视图的所有触摸事件都是在
contentView上收到的。尝试在contentView上禁用用户交互。 -
我用这样的代码做了一个测试项目,
touches工作正常。从故事板附加CustomUIView,评论contentView。自己试试吧。