swift - 如何在父 View Controller 中为动态创建的按钮创建处理程序?

标签 swift xcode6

我从 ViewController 创建了一个 subview 。在 subview 中,创建了多个按钮。当点击任何创建的按钮时,我想调用父 View Controller 中的函数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 的引用并将其设置为按钮目标。

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)

    }
}

关于swift - 如何在父 View Controller 中为动态创建的按钮创建处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26585368/

相关文章:

ios - iOS 7/iOS 8 中的不同 View 外观

ios - 应用程序不在后台运行

swift - 在 Swift 中从 NSBundle 获取文件路径

json - 循环 Json 链接 Swift

ios - Swift - 如何从 gpx 文件中读取坐标

ios - UIScrollView 中 UIImageView 的对齐

iOS - 带集群的 Mapbox,MGLSymbolStyleLayer 不显示自定义图像

ios - Xcode 关闭自动完成问题

ios - 将图像从 UITabBarController 传递到 subview (Swift)

ios - UICollectionViewCell 忽略指定大小但尊重原点