[英]UIView touchesBegan not being called
我創建了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
以查看是否可以觸發此IBAction。 答案是肯定的。 beginTracking
。 但這也不會觸發。 以下是我可以從此CustomView的ViewHierarchy中看到的屬性:
<nil color>
(我也試圖將其設置為具有某種顏色。無法正常工作。) 非常感謝幫助!
請嘗試一下,這是由於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
感謝@Fahri Azimov的評論,原因是contentView
啟用了“用戶交互”。 因此,在傳遞給CustomUIView
之前,它消耗了所有觸摸事件。 我贊成他的評論。
課程是,xib文件的rootView不是CustomUIView
本身,而是其子級之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.