0
我從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)
}
}
謝謝你的迴應!這是朝着正確方向邁出的一步。也許我仍然在做錯事,但只有第一個創建的按鈕在點擊時執行「buttonTapped」。 – AthleteInAction 2014-10-27 11:09:36
不要緊!謝謝,你的解決方案是完美的! – AthleteInAction 2014-10-27 11:25:04