Swift 如何从表视图单元格中获取值
我需要从表视图单元格中获取价格 我需要另找一个VC 每次用户选择行时,我都需要转移价格 问题是我不知道如何正确地从tableView获取值 菜单视图控制器:Swift 如何从表视图单元格中获取值,swift,tableview,Swift,Tableview,我需要从表视图单元格中获取价格 我需要另找一个VC 每次用户选择行时,我都需要转移价格 问题是我不知道如何正确地从tableView获取值 菜单视图控制器: import UIKit class MenueViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var dishes: [Dish] = [] var totalSum = 0 override fu
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
如何获取该值?请注意,在您的
性能检查之前,不会调用didSelectRowAtIndexpath
。在这里,您可以找到一个详细的解释,包括关于您的问题以及如何解决问题的示例代码
此外,下面列出了多种方法来解决您的问题
- 使用
willSelectIndexpath
并捕获indexpath以在performsgue
方法中传递它
- 使用
didSelectIndexpath
并在内部执行segue
- 仅使用
didSelectIndexpath
,并在其中执行导航逻辑,不使用out segues
你不应该从数据源,var Dish:[Dish]
获取价格吗?嗨,菲尔森,你是如何转到另一家VC的?从MenuViewController到OrderViewController?我需要将totalSum的值输入我的OrderVC,例如,用户在单元格上点击2次并将VC更改为OrderVC,它需要显示2个单元格值的totalSum Hi MacUserT,我使用当前模式segue。因此,用户按下按钮并更改VCSo,当用户点击sell时,您将从您的Dish数组中获得相应的Dish对象,并使用它获取价格/总额。我的观点是,您应该使用的是数据源,而不是UI组件来获得正确的值,因为保存数据的是您的模型Dish
。。