How can I add data to the first row of a table before it is filled with MPmedia items from a query?

47 Views Asked by At

I have been slowly building a music player. I query album data to populate a table. If the user selects an album, we segue to a new screen to pick a song to play. I'd like to make the first row of the albums table (in the albums view controller), be a row called 'All Songs', but I haven't been able to figure out how to do that.

I have tried to use: insertRowsAtIndexPaths. But was unsuccessful.

    @IBOutlet var albumsTableView: UITableView!

    let qryAlbums = MPMediaQuery.albums()  // Query the albums

    // Set the cell in the table
    func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {

        // I am using the custom class that I created called: myCustomAlbumTableViewCell
        let cell = tableView.dequeueReusableCell(withIdentifier: "albumIdCell", for: indexPath) as! myCustomAlbumTableViewCell

        let rowItem = qryAlbums.collections![indexPath.row]

        cell.albumTitle.text = rowItem.items[0].albumTitle

        return cell
    }
1

There are 1 best solutions below

4
Kevin On BEST ANSWER

Just make sure that you are displaying one more row than you have query albums and then every time you need to get a query album you minus 1 from the indexPath.row

    @IBOutlet var albumsTableView: UITableView!

    let qryAlbums = MPMediaQuery.albums()  // Query the albums

    // Set the cell in the table
    func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {

        // I am using the custom class that I created called: myCustomAlbumTableViewCell
        let cell = tableView.dequeueReusableCell(withIdentifier: "albumIdCell", for: indexPath) as! myCustomAlbumTableViewCell

        if indexPath.row == 0 {
            cell.albumTitle.text = "All Songs"
        } else {

            let rowItem = qryAlbums.collections![indexPath.row-1]

            cell.albumTitle.text = rowItem.items[0].albumTitle
        }

        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) ->  Int {
        return qryAlbums.collections! .count + 1
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row > 0 {
            let rowItem = qryAlbums.collections![indexPath.row-1]
        }
    }