Swift 如何在父视图控制器中为动态创建的按钮创建处理程序?

Swift 如何在父视图控制器中为动态创建的按钮创建处理程序?,swift,xcode6,Swift,Xcode6,我从ViewController创建了一个子视图。在子视图中创建了多个按钮。当点击任何创建的按钮时,我想调用父视图控制器中的函数buttonTapped() class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var bestTeamEver = SFGiants(frame: CGRect(x: 0, y: 100, width: view.bo

我从
ViewController
创建了一个子视图。在
子视图中
创建了多个按钮。当点击任何创建的按钮时,我想调用父视图控制器中的函数
buttonTapped()

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)
    }

}

您可以创建自定义init方法,并将引用传递给父viewController,然后将其设置为button target

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)

    }
}

谢谢你的回复!这是朝着正确方向迈出的一步。也许我还是做错了什么,但只有创建的第一个按钮在点击时执行“buttonTapped”。没关系!谢谢,你的解决方案是完美的!