我创建了简单按钮 - class Btn: UIControl
,然后添加到父视图。在我的Btn
课程中,我有override func touchesBegan
。
当我点击按钮时,为什么touchesBegan
无法调用?
我认为,我的Btn
扩展UIControl
和Btn
必须致电touchesBegan
。
我的代码:
导入UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// add my button
let button = Btn()
view.addSubview(button)
}
}
class Btn: UIControl {
fileprivate let button: UIButton = {
let swapButton = UIButton()
let size = CGFloat(50)
swapButton.frame.size = CGSize(width: size, height: size)
swapButton.backgroundColor = UIColor.green
return swapButton
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(button)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubview(button)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// Why it not called?
print("test")
}
}
答案 0 :(得分:2)
根据您的代码,使用以下游戏代码,您将了解正在发生的事情。虽然您的控件想要处理touchesBegan
回调,但它内部有一个UIButton
,它会消耗事件本身。在下面的示例中,内部按钮占据Btn
大小的四分之一(红色部分),如果单击它,则不会打印“测试”文本。 Btn
空间的其余部分(绿色部分)不包含任何会消耗touchesBegan
的其他视图,因此单击此处将打印“测试”文本。
我建议你看一下responder chain。
import PlaygroundSupport
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// add my button
let button = Btn(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.addSubview(button)
}
}
class Btn: UIControl {
fileprivate let button: UIButton = {
let swapButton = UIButton()
let size = CGFloat(50)
swapButton.frame.size = CGSize(width: size, height: size)
swapButton.backgroundColor = UIColor.green
return swapButton
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(button)
self.backgroundColor = .red
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubview(button)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// Why it not called?
print("test")
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = ViewController()