Получить индекс выбранной строки для использования при подготовке к переходу - PullRequest
0 голосов
/ 16 сентября 2018

Я хочу передать разные массивы из одного ViewController в другой в зависимости от выбранной строки.
Как получить индекс для выбранной строки?
Я пробовал это, но это не работает:

let toDetailVCSegue = "ToDetailVCSegue"

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: toDetailVCSegue, sender: indexPath)
    }



     func prepare(for segue: UIStoryboardSegue, sender: IndexPath?)
    {
        if segue.identifier == toDetailVCSegue
        {
        let destination = segue.destination as! DetailViewController
            if let indexPath = tableView.indexPathForSelectedRow{
                if indexPath.row == 0 {
                    destination.itemArray = namesArray
                    print("test")
                }
                if indexPath.row == 1 {
                    destination.itemArray = scoresArray
                }
                if indexPath.row == 2 {
                    destination.itemArray = timesArray
                }
                if indexPath.row == 3 {
                    destination.itemArray = completedArray
                }

            }
        }
    } 

Ответы [ 2 ]

0 голосов
/ 16 сентября 2018

Вы не должны изменять подпись prepare(for, иначе она не будет вызвана. Параметр sender должен быть Any?

Приведите параметр sender к IndexPath, и я рекомендую switch оператор

func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.identifier == toDetailVCSegue {
        let destination = segue.destination as! DetailViewController
        let indexPath = sender as! IndexPath
        switch indexPath.row {
          case 0: destination.itemArray = namesArray
          case 1: destination.itemArray = scoresArray
          case 2: destination.itemArray = timesArray             
          case 3: destination.itemArray = completedArray
          default: break
        }
    }
} 
0 голосов
/ 16 сентября 2018

Попробуйте это

let toDetailVCSegue = "ToDetailVCSegue"

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: toDetailVCSegue, sender: indexPath)
}

func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if  
        let destination = segue.destination as? DetailViewController, 
        let indexPath = sender as? IndexPath {

            switch indexPath.row {
            case 0: destination.itemArray = namesArray
            case 1: destination.itemArray = scoresArray
            case 2: destination.itemArray = timesArray             
            case 3: destination.itemArray = completedArray
            default: break

        }
    }

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