2015-08-30 30 views
2

一個動作在我的視圖控制器多個按鈕,我有10個按鈕。每個按鈕都有一個標籤和所有的按鈕調用相同的動作(單獨通過開關(sender.tag),情況0 - >殼體9區分選擇了哪個按鈕)。 我與IB做,連接所有的按鈕(@IBOutlet)相同的@IBAction,一切都很好。但是現在我想以編程的方式做到這一點,沒有IB。對於沒有IB

所以我刪除了@IBOutlet的和@IBAction創建新的按鈕(let myButton1 = UIBUtton())和一個新的動作(func newAction(sender: UIButton))。我爲所有新按鈕使用相同的選擇器嘗試了addTarget:,但應用程序崩潰。

任何人有一個想法解決它嗎?

+1

'target'應該是'self','action'應該是''newAction:''。注意冒號。 – vacawama

+0

一切都很好,謝謝! – TheBlueTurtle

回答

4

這應該工作:

func newAction(sender: UIButton) { 
    ... 
} 
... 
myButton1.addTarget(self, action: "newAction:", forControlEvents: .TouchUpInside) 
myButton2.addTarget(self, action: "newAction:", forControlEvents: .TouchUpInside) 
myButton3.addTarget(self, action: "newAction:", forControlEvents: .TouchUpInside) 
+0

確實有效!謝謝你們的快速響應 ! – TheBlueTurtle

0

這裏是我做的。我有兩個按鈕,一個在左邊,一個在右邊。我將標記值設置爲左側的0,右側的設置爲1enum是所有的標籤,所以你可以擁有儘可能多的按鈕。確保將故事板上的按鈕鏈接到相同的IBAction

class QuestionViewController: UIViewController { 

    @IBOutlet weak var leftButton: UIButton! 
    @IBOutlet weak var rightButton: UIButton! 

    enum ButtonType: Int { case Left = 0, Right } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    @IBAction func questionAnswered(sender: UIButton) { 
     switch(ButtonType(rawValue: sender.tag)!){ 
     case .Left: 
      leftButton.setTitle("left button", forState: UIControlState.Normal) 
     case .Right: 
      rightButton.setTitle("right button", forState: UIControlState.Normal) 
     } 

    } 
}