all! I'm trying to combine previous lessons with the Audio Player, but I'm running into an issue. I have a variable activeSong
which is equal to indexPath.row
using the method func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
. What happens is that when I print indexPath.row
its value is different form activeSong. Any idea why this might be happening. I think I'm doing something wrong with the func prepare(for segue: UIStoryboardSegue, sender: Any?)
method. Thanks!!
/
// MySongsController.swift
// Audio Player
//
// Created by Alex Gomez on 10/31/18.
// Copyright © 2018 Alex Gomez. All rights reserved.
//
import UIKit
var activeSong = -1
var isPlaying = false
class MySongsController: UITableViewController {
var songsList = [Song()]
@IBOutlet var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
if songsList.count == 1 && songsList[0].songTitle == "" {
songsList.remove(at: 0)
songsList.append(Song(songTitle: "El Colibri", songArtist: "Santiago Feliu", songFormat: "MP3"))
}
songsList.append(Song(songTitle: "Amargas Verdades", songArtist: "Santiago Feliu", songFormat: "MP3"))
table.reloadData()
// print("There are \(songsList.count) songs in the list")
// print("Active song is \(activeSong)")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// Number of cells
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songsList.count
}
// Cell title
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "Cell")
cell.textLabel?.text = "\(songsList[indexPath.row].songTitle) — \(songsList[indexPath.row].songArtist)"
return cell
}
// Go to "Now Playing" view once a cell is selected
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "toNowPlaying", sender: indexPath)
activeSong = indexPath.row
// print("—––––")
// print("Index Path row is \(indexPath.row)")
// print("Active song \(activeSong) — \(songsList[activeSong].songTitle)")
}
// Pass song information along to Now Playing view
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toNowPlaying" {
let nowPlayingView = segue.destination as! ViewController
nowPlayingView.playing = activeSong
}
}
}
You call performSegue
before setting activeSong
. Exchange the order.
Actually you don't need activeSong
. As you hand over the indexPath
anyway just use it:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toNowPlaying" {
let nowPlayingView = segue.destination as! ViewController
let indexPath = sender as! IndexPath
nowPlayingView.playing = indexPath.row
}
}