Неустранимая ошибка: индекс выходит за пределы диапазона при щелчке определенных ячеек для перехода - PullRequest
0 голосов
/ 07 июня 2019

Я пытаюсь создать переход, поэтому каждый раз, когда я щелкаю строку tableView, показываю другой ViewController с информацией о конкретной строке.

Я заполняю свои данные из Firestore.

В основном каждый документ содержит массив, а затем я заполняю строки массива в строках

var ingredientsArray = [Ingredients]()

func numberOfSections(in tableView: UITableView) -> Int {
        return ingredientsArray.count
    }

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ingredientsArray[section].compName.count
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        performSegue(withIdentifier: "SearchDetails", sender: self)
    }


     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "IngredientCell", for: indexPath) as! IngredientTableViewCell

        cell.populate(ingredient: ingredientsArray[indexPath.section])
        let item1 = ingredientsArray[indexPath.section].compName[indexPath.row]
        cell.ingredientNameLabel.text = ("\(item1)")

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? DetailViewController{

//HERE IS THE ERROR.
            destination.ingredient = ingredientsArray[(tableView.indexPathForSelectedRow?.row)!]

        }
    }

Когда я щелкаю несколько строк, мое приложение вылетает и выдает мне фатальную ошибку: индекс выходит за пределы диапазона

DetailViewController


class DetailViewController: UIViewController {

    @IBOutlet weak var compNameLbl: UILabel!

    var ingredient : Ingredients?

    override func viewDidLoad() {
        super.viewDidLoad()

        compNameLbl.text = "\((ingredient?.compName)!)"


    }
}

Также, когда я пытаюсь показать имя в метке, появляется весь массив.

1 Ответ

1 голос
/ 07 июня 2019

Получите строковое значение из массива compName и передайте значение

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? DetailViewController, let indexPath = tableView.indexPathForSelectedRow {
        destination.ingredient = ingredientsArray[indexPath.section].compName[indexPath.row]
    }
}

Измените тип ingredient на String в DetailViewController

class DetailViewController: UIViewController {    
    @IBOutlet weak var compNameLbl: UILabel!
    var ingredient : String?
    override func viewDidLoad() {
        super.viewDidLoad()
        compNameLbl.text = ingredient
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...