在派生类的代码中,应该手动重写所有父类中的IBAction方法,并在连接到子视图的控件上。
具体代码示例:
父类中的IBAction方法:
@IBAction func buttonAction(_ sender: UIButton) {
print("Button tapped!")
}
派生类中应手动重写:
@IBAction override func buttonAction(_ sender: UIButton) {
print("Button tapped in derived class!")
}
并将派生类中的方法连接到子视图上,例如在自定义视图类中添加connect方法:
func connect() {
for subview in self.subviews {
if let button = subview as? UIButton {
button.addTarget(self, action: #selector(self.buttonAction(_:)), for: .touchUpInside)
}
}
}
然后在实例化子视图时调用connect方法:
let customView = CustomView()
customView.connect()
parentView.addSubview(customView)