2

我有一個動態桌面視圖,其中有一個按鈕,當按下時播放歌曲的原型單元格。更改在UITableview中按下的特定按鈕的圖像

我想要按鈕上的背景圖像,當用戶按下按鈕播放歌曲時變爲「停止」圖標,並且當用戶按下它時變爲「播放」圖標再一次阻止這首歌。

要做到這一點,我一直在試圖使用方法: [self.beatPlayButton setBackgroundImage:[UIImageimageNamed:@"play.png"]forState:UIControlStateNormal];

我的問題是,我還沒有想出如何,因爲我使用的原型,被按下的行中僅更改按鈕細胞。我一直希望找到像didSelectObjectAtRow:atIndexPath:這樣的方法,因爲didSelectRowAtIndexPath:會在按下該行時觸發,但不會觸發按鈕(除非我錯了)。也許我應該使用標籤?我不確定。任何指針將不勝感激。我的代碼不在didSelectRowAtIndexPath之內。

下面是示例代碼 -

- (IBAction)playStopBeat:(UIButton*)sender event:(id)event { 
    NSSet *touches = [event allTouches]; 
    UITouch *touch = [touches anyObject]; 
    CGPoint currentTouchPosition = [touch locationInView:self.tableView]; 
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition]; 
    if([self.audioPlayer isPlaying]) 
    { 
     [self.beatPlayButton setBackgroundImage:[UIImage imageNamed:@"play.png"]forState:UIControlStateNormal]; 
     [self.audioPlayer stop]; 
     self.isPlaying = NO; 
     self.audioPlayer = nil; 
    } 
    else { 

     if (indexPath.row == 0) { 
      [self.beatPlayButton setImage:[UIImage imageNamed:@"stop.png"] forState: UIControlStateNormal]; 
     } 
     else if (indexPath.row == 1){ 
      [self.beatPlayButton setBackgroundImage:[UIImage imageNamed:@"stop.png"]forState:UIControlStateNormal]; 
     } 
     else if (indexPath.row == 2){ 
... 
//code to play song 
+0

是在'didSelectRowAtIndexPath'中發生的操作還是在按鈕發送的某些操作中? –

+0

你能提供一些代碼嗎?什麼動作與按鈕相關聯? – sergio

+0

我已更新我的問題以提供更多上下文。謝謝。 –

回答

2

使用標籤,像你這樣的建議。在您的cellForRowAtIndexPath方法給每一個小區的標籤:

cell.tag = indexPath.row; 

還設置每個目標的細胞:

[cell.playButton addTarget:self action:@selector(play:)forControlEvents:UIControlEventTouchUpInside]; 

然後在您的遊戲方法,用你的標記爲您的陣列或W/E:

- (IBAction)play:sender 
{ 
    UITableViewCell *cell = (UITableViewCell *)sender; 
    NSLog(@"tag = %d", cell.tag); 

    if(tag == 0) 
    { 
      //you could also use a switch statement 
    } else if(tag == 1) { 

    } 
} 

::編輯::(回答評論)

要禁用其他按鈕,在你的PLA y方法:

- (IBAction)play:sender 
{ 
    ......... 
    ....other code.... 

    UITableViewCell *cell = (UITableViewCell *)sender; 

    for(int i = 0; i < [dataArray count]; i++) 
    { 
     UITableViewCell *tempCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]; 

     if(tempCell.tag != cell.tag) 
     { 

      [cell.playButton setEnabled:NO]; 
     } 
    } 
} 

儘管如此,歌曲播放完畢後,您必須將它們全部設置爲啓用。這將在MediaPlayers委託方法中完成:didFinishPlaying。

+0

感謝我的朋友。我能夠得到這個工作與你的幫助。 –

+0

你知不知道是否有一種方法可以禁止與其他標籤索引處的按鈕進行交互?例如,如果我有5行,並且我在標籤#2處按下按鈕,則標籤0-1和3-5處的按鈕將被禁用。如果你知道,那麼我可以提出另一個問題,並給它一個鏈接,以便你可以回答它。 –

+0

@OrpheusMercury我只是給我的原始答案添加了一些代碼,讓我知道是否有幫助。我相信它應該是有效的,但我沒有在xcode中測試。 – RyanG

2

由於您使用的是目標/動作,發件人參數將包含被點擊的按鈕。而不是將該按鈕稱爲self.beatPlayButton,只是使用發件人,因此[sender setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];

+0

我意識到這一點並對其進行了調整。你是絕對正確的。 +1 –