【问题标题】:Playing songs with button in UITableView在 UITableView 中使用按钮播放歌曲
【发布时间】:2012-04-07 03:32:38
【问题描述】:

我正在创建一个自定义表格,该表格有一个按钮,允许用户在按下时预览歌曲。我的大部分代码都有效,但我还没有弄清楚如何向播放器传递与按下按钮的行相对应的特定歌曲。

例如:如果我有两排,#1 说 Jay Z,#2 说 Red Hot Chili Peppers,我想按下 #1 中的按钮来播放 Jay,按下 #2 中的按钮来播放 Peppers。简单的。我的代码有缺陷,无论我按哪一行的按钮,我都只能播放相同的歌曲。

我知道为什么会这样,但我不知道如何解决。我只是想知道是否有人可以用几行来打我,可以为我指明正确的方向。

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

我需要为此创建一个方法还是我忽略了什么?

谢谢!

【问题讨论】:

    标签: objective-c cocoa-touch uitableview ios5


    【解决方案1】:

    您还可以设置您在tableView: cellForRowAtIndexPath: 期间创建的每个按钮的tag 属性,然后当您的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]);
    }
    

    【讨论】:

      【解决方案2】:

      类似

      - (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
      }
      

      【讨论】:

        【解决方案3】:

        类似于 tableView: cellForRowAtIndexPath: 将您的按钮标签作为 index.row 并将下面的函数绑定到按钮的 touchup 事件内

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

        我想这会对你有所帮助!

        【讨论】:

        • 谢谢!我将尝试我收到的所有内容,看看哪个效果最好。
        猜你喜欢
        • 2021-02-27
        • 1970-01-01
        • 2018-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多