我从subview
创建了ViewController
。在subview
中,创建了多个按钮。当点击任何创建的按钮时,我想调用父buttonTapped()
中的函数view controller
。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var bestTeamEver = SFGiants(frame: CGRect(x: 0, y: 100, width: view.bounds.width, height: 40))
view.addSubview(bestTeamEver)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func buttonTapped(){
NSLog("BUTTON INSIDE SFGIANTS TAPPPED")
}
}
class SFGiants: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
for i in 0...10 {
var new_x = i*44
var button = UIButton(frame: CGRect(x: new_x, y: 0, width: 40, height: 40))
button.backgroundColor = UIColor.orangeColor()
// Call buttonTapped() in parent view controller
button.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchDown)
self.addSubview(button)
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
答案 0 :(得分:1)
您可以创建自定义init方法,并可以将引用传递给父viewController并将其设置为按钮目标。
init(frame: CGRect actionListener:UIViewController) {
super.init(frame: frame)
for i in 0...10 {
var new_x = i*44
var button = UIButton(frame: CGRect(x: new_x, y: 0, width: 40, height: 40))
button.backgroundColor = UIColor.orangeColor()
// Call buttonTapped() in parent view controller
button.addTarget(actionListener, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchDown)
self.addSubview(button)
}
}