gpt4 book ai didi

ios - Xcode TableViewCell 推送到 ViewController

转载 作者:行者123 更新时间:2023-11-30 12:33:30 24 4
gpt4 key购买 nike

我正在创建一个应用程序,其中显示膳食列表,当您单击其中一个时,它会显示该膳食的更多详细信息。

当我运行它时,它会在 table 上显示餐食,但是当我单击餐食时,它只会提供餐食模板,

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 中显示项目数据,但我在底部收到默认错误

最佳答案

您可以在 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)
}

关于ios - Xcode TableViewCell 推送到 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43153272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com