英文:
I can not pass data from one View Controller to another
问题
I will only translate the non-code parts of your text, as you requested:
"Could you help me with my code. I can not pass ma data on prepare segue. // cannot assign value of type Response to type Meals. I don't know what I do wrong. I just need a help with line prepare for segue. It is a last line of code. Will be glad for any help. thank you!
Please check it here."
英文:
Could you help me with my code. I can not pass ma data on prepare segue. // cannot assign value of type Response to type Meals. I don't know what I do wrong. I just need a help with line prepare for segue. It is a last line of code. Will be glad for any help. thank you!
struct Response: Codable {
var meals: [Meals]?
}
struct Meals: Codable {
var strMeal: String?
var strMealThumb: String?
var idMeal: String?
}
class MealsViewController: UIViewController {
//var results: Response?
var meals : Meals = Meals()
@IBOutlet weak var mealImage: UIImageView!
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var idLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
nameLbl.text = meals.strMeal
idLbl.text = meals.idMeal
}
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var resultsData: Response?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
getResultData {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
tableView.delegate = self
tableView.dataSource = self
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
resultsData?.meals?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
let meal = resultsData?.meals
cell.textLabel?.text = meal![indexPath.row].strMeal
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? MealsViewController {
destination.meals = resultsData // cannot assign value of type Response to type Meals
}
}
Please check it here.
答案1
得分: 1
你的 meals
应该在 viewDidLoad
外部声明。
应该如下所示。
class MealsViewController: UIViewController {
var meals: Meals = Meals()
override func viewDidLoad() {
super.viewDidLoad()
print("你的餐名是==\(meals.strMeal ?? "")")
}
}
英文:
Your meals
should be outside the viewDidLoad
It should be as below.
class MealsViewController : UIViewController {
var meals : Meals = Meals()
override func viewDidLoad() {
super.viewDidLoad()
print("your meal name is==\(meals.strMeal ?? "")")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论