rocketman240 rocketman240 - 7 months ago 8
Swift Question

Tags and MPMediaItems in a custom cell

I have a UITableView using a custom cell that is populated with MPMediaItems and buttons (among other things). I'm trying to perform an action with the MPMediaItem of a particular cell, with respect to which button is tapped, not via didSelectRowAtIndexPath. I've tried various approaches and I believe tags are likely the way to go but I can't get the correct implementation. I can only seem to get the very first item of the collection or the last. What is the correct way to set up tags when handling MPMediaItems? Some code is below...

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell : SongCell = self.songsTableView.dequeueReusableCellWithIdentifier("cell") as! SongCell
cell.button.addTarget(self, action: #selector(handleSelection), forControlEvents: .TouchUpInside)
cell.tag = indexPath.row //removing this line results in getting the first item in the collection, using it results in the last (understandably so)
index = cell.tag
return cell
}

@IBAction func handleSelection(sender: AnyObject)
{
let songToHandle = tableData.items![index!]
queryAsCollectionItems?.append()
}

Answer

Try to bellow code.

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell     {
         let cell : SongCell = self.songsTableView.dequeueReusableCellWithIdentifier("cell") as! SongCell
         cell.button.addTarget(self, action: #selector(handleSelection), forControlEvents: .TouchUpInside)
         cell.button = indexPath.row
         return cell
     }

     @IBAction func handleSelection(sender: AnyObject) {
          println(sender.tag)
          let songToHandle = tableData.items![sender.tag!]
          queryAsCollectionItems?.append()
     }
Comments