我创建了简单的按钮- 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")
}
}
发布于 2018-01-28 13:04:22
根据您的代码,使用下面的操场代码,您将了解正在发生的事情。当您的控件想要处理touchesBegan
回调时,它的内部有一个UIButton
,它会消耗事件本身。在下面的示例中,内部按钮是Btn
大小的四分之一(红色部分),如果单击它,“测试”文本将不会被打印出来。Btn
空间的其余部分(绿色部分)不包含将消耗touchesBegan
的任何其他视图,因此单击那里将打印"test“文本。
我建议你看看应答链。
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()
https://stackoverflow.com/questions/48486432
复制相似问题