ios - 表格视图不更新
问题描述
我正在尝试为餐厅制作一个订购食品的应用程序,当我第一次将物品添加到购物车时,表格视图会加载我制作的单例数组。但是当我返回菜单并选择另一个项目时,数组已更新,但购物车的表格视图没有,我正在使用 tabbarcontroller。尝试在不同的地方使用 tableview.reloadData() 仍然没有出现添加到数组的新数据
class CartVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var priceLbl: UILabel!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
updateView()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataService.instance.cartItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cartCell") as? CartCell{
let item = DataService.instance.cartItems[indexPath.row]
cell.configCell(cart: item)
return cell
} else {
return UITableViewCell()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
DataService.instance.cartItems.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .automatic)
updateView()
tableView.endUpdates()
}
}
func updateView(){
var sum = 0
for item in DataService.instance.cartItems{
sum += item.itemPrice * item.quantity
print(item.itemPrice)
}
priceLbl.text = "$\(sum)"
}
@IBAction func orderPressed(_ sender: Any) {
// upload order to firebase, clear cart and move to orderVC
}
}
解决方案
在 tabbar 中每次都viewDidLoad
没有被调用,所以你需要重新加载viewWillAppear
or中的数据viewDidAppear
。这是参考。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
updateView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
推荐阅读
- excel - 有没有办法根据从文本框输入的数字在用户窗体中循环命令按钮?
- spring-boot - Spring boot 2.1.4 Autowired 在启动期间有效,但在创建新 Pojo 实例时无效
- axis - websphere 9 上的 jax-rpc 网络服务
- google-cloud-platform - 如何在 GCP Compute Engine 中以同一用户身份从不同机器登录 VM
- .htaccess - 使用 htaccess 中的 RewriteRule 将 http://example.com/wp/ 更改为 http://example.com/
- android - 使所有 APK 处于非活动状态,而不是取消发布应用程序本身
- angular - 甚至无法运行 Angular Material 的基础知识——尝试关注 material.angular.io 但现在更加困惑
- python - 扩展欧几里得算法的不同实现产生不同的结果?
- c++ - 接受对抽象类的 const 引用的 C++ 构造函数无法初始化 std::map
- aptana3 - Aptana Studio 3 启动错误 - Java 问题