Функция Swift 4 подготовить (для segue: UIStoryboardSegue, sender: Any?), Не обновляя переменную Int с помощью indexPath.row - PullRequest
0 голосов
/ 01 ноября 2018

все! Я пытаюсь объединить предыдущие уроки с аудиоплеером, но у меня возникла проблема. У меня есть переменная activeSong, которая равна indexPath.row с использованием метода func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath). Что происходит, когда я печатаю indexPath.row, его значение отличается от activeSong. Любая идея, почему это может происходить. Я думаю, что я делаю что-то не так с методом func prepare(for segue: UIStoryboardSegue, sender: Any?). Спасибо !!

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

Ответы [ 2 ]

0 голосов
/ 01 ноября 2018

Вы звоните performSegue перед установкой activeSong. Обменять заказ.

На самом деле вам не нужно activeSong. Как только вы передадите indexPath, просто используйте его:

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
    }
}
0 голосов
/ 01 ноября 2018

Изменение performSegue(withIdentifier: "toNowPlaying", sender: indexPath)

до performSegue(withIdentifier: "toNowPlaying", sender: self)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...