用UITableView播放按钮的歌曲

问题描述:

我正在创建一个自定义表格,其中包含一个允许用户在按下时预览歌曲的按钮。我的大部分代码都可以工作,但我还没有想出如何将播放器传递给与按下按钮的行相对应的特定歌曲。用UITableView播放按钮的歌曲

例如:如果我有两行,#1说Jay Z和#2说红辣椒,我想按下#1按钮来播放Jay,并按下#2中的按钮来获得辣椒。简单。我的代码有缺陷,无论按下哪一行按钮,我都只能播放同一首歌曲。

我知道这是为什么发生,但我不知道如何解决它。我只是想知道是否有人可以用几条线打我,这可能会让我指向正确的方向。

我不能使用didSelectRowAtIndexPath,因为我希望在选择行本身时发生其他事情。

我需要为此创建一个方法还是有一些我忽略了的东西?

谢谢!

您还可以设置您创建的每个按钮的tag财产时tableView: cellForRowAtIndexPath:,那么当被称为你的buttonTapped事件,仰望sender并找到其tag。 UIView的tag属性仅用于解决这类问题。

如果您需要更多信息,您可以创建一个UIButton子类,用于存储任何或所有关于相关歌曲的信息。再次,您在cellForRowAtIndexPath期间设置该信息,以便在点按该按钮时进行检索。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; 
{ 
    // Dequeue a cell and set its usual properties. 
    // ... 

    UIButton *playButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [playButton addTarget:self action:@selector(playSelected:) forControlEvents:UIControlEventTouchUpInside]; 
    // This assumes you only have one group of cells, so don't need to worry about the first index. If you have multiple groups, you'll need more sophisticated indexing to guarantee unique tag numbers. 
    [playButton setTag:[indexPath indexAtPosition:1]]; 

    // ... 
    // Also need to set the size and other formatting on the play button, then make it the cell's accessoryView. 
    // For more efficiency, don't create a new play button if you dequeued a cell containing one - just set its tag appropriately. 
} 

- (void) playSelected:(id) sender; 
{ 
    NSLog(@"Play song number %d", [sender tag]); 
} 
+0

谢谢!我要去检查一下。 – 2012-04-07 16:31:51

喜欢的东西

- (void)buttonTapped:(UIView *)sender; 
{ 
    CGPoint pointInTableView = [sender convertPoint:sender.bounds.origin toView:self.tableView]; 
    NSIndexPath *tappedRow = [self.tableView indexPathForRowAtPoint:pointInTableView]; 

    // get song that should be played with indexPath and play it 
} 

像中的tableView:的cellForRowAtIndexPath:给你的按钮标记为index.row和下面的功能结合到按钮的触内部事件

-(void)button_click:(UIView*)sender 
{ 
    NSInteger *index = sender.tag; 
    //play song on that index 
} 

我认为这将有助于您!

+0

谢谢!我会尝试我收到的所有内容,并看看哪个最好。 – 2012-04-07 16:32:24