我已经创建了一个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
从未被调用。
我已经在Google和StackOverflow上搜索了3个小时,但仍然找不到任何有效的解决方案...
以下是我尝试过的:
- 确保所有的父视图都启用了用户交互。我甚至检查了视图层次结构。
- 添加了一个 touchUpInside 的
IBAction
看看是否可以触发该 IBAction。答案是肯定的。 - 尝试子类化 UIControl 并重写
beginTracking
,但它也没有被触发。
以下是我可以从此自定义视图的 ViewHierarchy 中看到的属性:
- 已启用
- 用户交互已启用
- 多点触控关闭
- 透明度为 1
- 背景
<nil color>
(我还尝试将其设置为具有颜色。但并没有起作用。) - 不透明开启
- 隐藏关闭
- 清除图形上下文开启
- 剪辑边界关闭
- 自动调整子视图开启
非常感谢您的帮助!
contentView
是什么? - mugxtouches
正常工作。附上了从storyboard中提取的CustomUIView
,并注释了contentView
。你可以自己试试看。 - mugx