如何从表格视图单元格中获取值

问题描述 投票:0回答:1

我需要从表视图单元格中获取价格,我需要得到它的另一个VCI需要转移价格,每次当用户选择行的问题是,我不知道如何正确地从tableViewMenueViewController的值。

import UIKit

class MenueViewController: UIViewController {

   @IBOutlet weak var tableView: UITableView!

   var dishes: [Dish] = []

   var totalSum = 0

   override func viewDidLoad() {
       super.viewDidLoad()

       dishes = createArray()

       tableView.delegate = self
       tableView.dataSource = self
       tableView.backgroundColor = .white
       navigationItem.title = "Меню"

   }

   func createArray() -> [Dish] {

       var tempDishes: [Dish] = []

       let dish1 = Dish(image: UIImage.init(named: "plovKebab")!, title: "Плов Кебаб", price: 169, type: "Основные Блюда")
       let dish2 = Dish(image: UIImage.init(named: "plovKebabShafran")!, title: "Плов Кебаб Шафран", price: 169, type: "Основные Блюда")

       tempDishes.append(dish1)
       tempDishes.append(dish2)

       return tempDishes
   }

}
extension MenueViewController: UITableViewDataSource, UITableViewDelegate {
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return dishes.count
   }

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let dish = dishes[indexPath.row]

       let cell = tableView.dequeueReusableCell(withIdentifier: "MenueCell") as! MenueCell
       cell.setDish(dish: dish)


       return cell
   }
   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       let dish = dishes[indexPath.row]
       totalSum += dish.price //the place where I tried to take price
       print(totalSum)
   }
}

VC,我们需要在哪里获取该价格。

import UIKit

class OrderViewController: UIViewController {

   @IBOutlet weak var totalPriceLabel: UILabel!

   var totalPrice: MenueViewController?
   var sum:Int?
   override func viewDidLoad() {
       super.viewDidLoad()

       if let price = sum {

       totalPriceLabel.text = String(totalPrice?.totalSum)

       }
   }

总和的值是0,我怎么才能得到这个值?

swift tableview
1个回答
0
投票

请注意 didSelectRowAtIndexpath 不会比你的 performSegue. 这时 联系,你可以找到一个详细的解释,包括关于你的问题和如何解决它的示例代码。

另外,下面还列出了多种方法来解决你的问题。

  • 使用 willSelectIndexpath 并捕获indexpath将其传递到 performSegue 办法
  • 使用 didSelectIndexpath 并在里面进行转场
  • 只能使用 didSelectIndexpath 并在其中执行导航逻辑,而不需要转场
© www.soinside.com 2019 - 2024. All rights reserved.