2014-03-05 52 views
0

我試圖與音板應用程序一起玩,我需要在視圖控制器上多達50個按鈕(每個聲音都有一個)。另外,我想完全編程地製作按鈕(和音頻播放器代碼),因爲在故事板和.h/.m文件之間切換是一件令人討厭的事情。相反,複製和粘貼相同的按鈕碼50倍,我使用這個for循環,才能使按鈕對我來說:通過多個按鈕播放多個音頻文件

NSUInteger i; 
int xCoord=0; 
int yCoord=0; 
int buttonWidth=100; 
int buttonHeight=50; 
int buffer = 10; 
for (i = 1; i <= 100; i++) 
{ 
    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    aButton.frame  = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight); 
    [aButton addTarget:self action:@selector(playAudioMethod) forControlEvents:UIControlEventTouchUpInside]; 
    [scrollView addSubview:aButton]; 

    yCoord += buttonHeight + buffer; 
} 
[scrollView setContentSize:CGSizeMake(700, yCoord)]; 

的playAudioMethod在選擇的按鈕單擊事件只是扮演一個聲音。怎麼能有50個聲音,每個聲音對應一個單獨的按鈕?對不起,如果這是一個非常基本的問題,我仍然在學習目標C.謝謝!

編輯:

這裏的playAudioMethod:

- (void) playButtonSound:(id)inSender 
{ 
    AudioServicesPlaySystemSound(self.SoundID); 
} 

它基本上只是扮演SoundID屬性,我通過一個聲音文件到通過這樣的:

NSURL *buttonURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"medic_taunts01" ofType:@"wav"]]; 
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)buttonURL, &SoundID); 
    self.SoundID = SoundID; 
+0

顯示您playAudioMethod方法 –

+0

完成,我只是說玩音頻的方法。 – Quikdart

回答

0

playAudioMethod有一個參數,這是sendersender是生成消息的按鈕。

- (void)playAudioMethod:(id)sender 
{ 
    UIButton *button = (UIButton *)sender; 
    switch (button.tag) 
    { 
      //.... 
    } 
} 

您可以使用該按鈕的tag屬性存儲的值,例如,你可以存儲一個整數,它允許您識別在playAudioMethod按鈕,或者你可以直接存儲音頻資源的名稱。

+0

我會嘗試一下,但是我可以在for循環中增加標記嗎?也許使用像這樣的東西:[button tag ++]?謝謝。 – Quikdart

+0

你寧願做一些像'button.tag = i' – Merlevede

+0

謝謝!代碼完美工作。 – Quikdart