我创建了一个UIView
的子类,并通过引用xib文件添加到Views中。
我覆盖了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搜索和stackoverflowed,已经尝试了3个小时,但找不到任何解决这个简单问题的方法....
以下是我的尝试:
IBAction
touchUpInside以查看是否可以触发此IBAction。答案是肯定的。beginTracking
。但它也没有触发。以下是我可以从此CustomView的ViewHierarchy中看到的属性:
<nil color>
(我也尝试将其设置为颜色。不工作。)非常感谢帮助!
答案 0 :(得分:0)
请试试这个,因为 CustomView
的框架class CustomUIView: UIView {
var contentView: UIView!
override init (frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init? (coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func loadFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
private func commonInit () {
contentView = self.loadFromNib()
addSubview(contentView)
contentView.frame = self.bounds
self .isUserInteractionEnabled = true
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)
}
}
我可以在控制台中看到日志
在 ViewController 中拖动一个 UIView ,并将 customview 类设置为 CustomUIView
答案 1 :(得分:0)
感谢@Fahri Azimov的评论,原因是contentView
启用了用户交互。因此,它会在传递给CustomUIView
之前消耗所有触摸事件。我赞成他的评论。
经验教训是,xib文件的rootView不是CustomUIView
本身,而是其子项之一。