Учебное пособие по разработке Xcode от Apple: «Поток 1. Неустранимая ошибка. Удаленная ячейка не является экземпляром MealTableViewCell». - PullRequest
0 голосов
/ 28 февраля 2020

Я новичок в Xcode / swift и уже 2 недели пытаюсь выполнить sh руководство по разработке iOS приложений (Swift) от apple для создания приложения FoodTracker. Благодаря SOF мне удалось перейти на последнюю страницу, но теперь я застрял в ошибке в заголовке.

Моя цель, чтобы приложение работало на 100%. Я даже скопировал страницу с кодом, чтобы посмотреть, смогу ли я заставить ее работать таким образом, но безрезультатно. До этого момента приложение функционировало нормально. Последний шаг, который я предпринял, состоял в том, чтобы приложение поместило три примера в список (первая страница приложения). Вторая страница (где пользователь может вводить информацию) не связана с первым контроллером табличного представления, но есть 3 примера продуктов, которые к настоящему времени должны отображаться в списке.

import UIKit

class MealTableViewController: UITableViewController {

    //MARK: Properties

    var meals = [Meal]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Load the sample data.
        loadSampleMeals()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //MARK: - Table view data source


    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return meals.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // Table view cells are reused and should be dequeued using a cell identifier.
        let cellIdentifier = "MealTableViewCell"

        **guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MealTableViewCell  else {
            fatalError("The dequeued cell is not an instance of MealTableViewCell.")**
        }

        // Fetches the appropriate meal for the data source layout.
        let meal = meals[indexPath.row]

        cell.nameLabel.text = meal.name
        cell.photoImageView.image = meal.photo
        cell.ratingControl.rating = meal.rating

        return cell
    }


    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    //MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    //MARK: Private Methods

    private func loadSampleMeals() {

        let photo1 = UIImage(named: "meal1")
        let photo2 = UIImage(named: "meal2")
        let photo3 = UIImage(named: "meal3")

        guard let meal1 = Meal(name: "Caprese Salad", photo: photo1, rating: 4) else {
            fatalError("Unable to instantiate meal1")
        }

        guard let meal2 = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5) else {
            fatalError("Unable to instantiate meal2")
        }

        guard let meal3 = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3) else {
            fatalError("Unable to instantiate meal2")
        }

        meals += [meal1, meal2, meal3]
    }

}

1 Ответ

0 голосов
/ 28 февраля 2020

При использовании пользовательского UITableViewCell, убедитесь, что вы используете свое имя класса в раскадровке, в вашем случае MealTableViewCell. Это необходимо сделать в двух местах:

  1. В инспекторе Атрибутов -> установите поле Идентификатор на MealTableViewCell
  2. В инспекторе Идентификационных данных -> установите поле Класс на MealTableViewCell

Легко забыть одного из них.

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