【发布时间】:2020-05-12 08:07:56
【问题描述】:
我需要从表格视图单元格中获取价格 我需要找另一个VC 每次用户选择行时我都需要转移价格 问题是我不知道如何正确地从 tableView 获取值 MenueViewController:
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)
}
}
sum的值为0 如何获得价值?
【问题讨论】:
-
不应该从数据源获取价格,改为
var dishes: [Dish]吗? -
嗨,Fillsondy,你是如何转到其他 VC 的?从 MenuViewController 到 OrderViewController?
-
我需要将totalSum的值带到我的OrderVC中,例如用户在单元格处点击2次并将VC更改为OrderVC,它需要显示2个单元格值的totalSum
-
嗨 MacUserT,我使用 Present Modally segue。所以用户按下按钮并更改 VC
-
因此,当用户点击卖出时,您会从您的盘子数组中获取相应的 Dish 对象并使用它来获取价格/总和。我的观点是,你应该使用数据源而不是 UI 组件来获得正确的值,因为你的模型
Dish保存了数据..