Xcode TableViewCell推送到ViewController

时间:2017-04-01 05:42:16

标签: ios objective-c swift xcode

我正在创建一个应用程序,其中显示餐桌列表,当您点击其中一个时,它会更详细地显示用餐。

当我运行它时会在餐桌上显示餐点,但是当我点击餐时它只是给出了餐食模板,

This is a picture of the storyboard 这是我用于TableViewController显示项目的代码

private func loadSampleMeals() {

        let photo1 = UIImage(named: "Sprite")
        let photo2 = UIImage(named: "HotCheetos")
        let photo3 = UIImage(named: "Nachos")

        guard let meal1 = Meal(name: "Sprite", price: "$1.50", photo: photo1, rating: 0, calories: "Calories: 129", description: "Description: A refreshing lemon-lime soda") else {
            fatalError("Unable to instantiate meal1")
        }

        guard let meal2 = Meal(name: "Hot Cheetos", price: "$1.50", photo: photo2, rating: 0, calories: "Calories: 160", description: "Description: A spicy version of original cheetos") else {
            fatalError("Unable to instantiate meal2")
        }

        guard let meal3 = Meal(name: "Nachos", price: "$1.50", photo: photo3, rating: 0, calories: "Calories: 436", description: "Description: Tortilla chips with a side of smooth nacho cheese") else {
            fatalError("Unable to instantiate meal2")
        }

        meals += [meal1, meal2, meal3]
    }


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

        switch(segue.identifier ?? "") {
            case "ShowDetail":
            guard let mealDetailViewController = segue.destination as? MealViewController else {
                    fatalError("Unexpected destination: \(segue.destination)")
            }

            guard let selectedMealCell = sender as? MealTableViewCell else {
                fatalError("Unexpected sender: \(sender)")
            }

            guard let indexPath = tableView.indexPath(for: selectedMealCell) else {
                fatalError("The selected cell is not being displayed by the table")
            }

            let selectedMeal = meals[indexPath.row]
            mealDetailViewController.meal = selectedMeal

        default:
            fatalError("Unexpected Segue Identifier; \(segue.identifier)")
        }
    }

在代码中,guard语句应该使它在ViewController中显示项目数据,但是我在底部得到了默认错误

1 个答案:

答案 0 :(得分:0)

您可以在didSelectRowAt上访问用餐对象,例如,您有一系列用餐来生成细胞而且只有一个部分

var meals: [Meal] 

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

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

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedMeal = meals[indexPath.row]
    let mealDetailsVC = MealDetailsViewController()
    mealDetailsVC.meal = selectedMeal

    navigationController?.pushViewController(mealDetailsVC, animated: true)
}