关闭viewController后重新加载tableView [英] Reload tableView after dismiss a viewController
问题描述
我有一个内部有TableView的ViewController(VCA).从该ViewController可以调用另一个ViewController(VCB).在第二个VC中,可以将一个项目添加到用于在VCA中填充TableView的plist中.问题是,当我保存新项目并关闭VCB时,无法在VCA中重新加载TableView.
I have a ViewController(VCA) with a TableView inside. From this ViewController it is possibile to call another ViewController (VCB). In this second VC it is possibile add an item to the plist used to populate the TableView in VCA. The problem is that when I save the new item and dismiss the VCB, I can't reload the TableView in VCA.
我发现了很多例子:
您怎么能在Swift中取消以模态显示的视图控制器后重新加载ViewController?
如何调用重新加载表迅速调用dismissViewController之后查看?
阅读后,我尝试使用此代码:
after reading i tried with this code:
**IN VCB**
import UIKit
protocol AddItemDelegateProtocol {
func didAddItem()
}
class VCB: UIViewController {
var delegate : AddItemDelegateProtocol?
...
}
@IBAction func saveButton(_ sender: Any) {
....
self.delegate?.didAddItem()
dismiss(animated: true, completion: nil)
}
**In VCA**
class VCA: UIViewController, UITableViewDelegate, UITableViewDataSource, AddItemDelegateProtocol {
let addItemVC = VCB()
...
override func viewDidLoad() {
super.viewDidLoad()
addItemVC.delegate = self
...
}
func didAddItem() {
self.tableView.reloadData()
}
但这不起作用.我不 了解我错了.可以 你帮我吗?
but this doesn't work. I don't understand where I'm wrong. Could you help me?
我的解决方案 我是这样解决的:
我创建了一个单例,并在其中声明:
I've created a singleton in which I declare:
class DataManager {
static let shared = DataManager()
var firstVC = VCA()
.....
}
然后,在VCA的viewDidLoad中:
DataManager.shared.firstVC = self
现在,在VCB的saveButton 中,我可以调用:
now, in the saveButton of VCB, i can call:
@IBAction func saveButton(_ sender: Any) {
........
DataManager.shared.firstVC.tableView.reloadData()
dismiss(animated: true, completion: nil)
}
推荐答案
您可以通过两种方式执行此操作:-
you can do this in two way :-
1)
在VCA中做一件事
1)
Do One thing in VCA
VCA
override func viewWillAppear(_ animated: Bool){
tableView.reloadData()
}
如果无法解决,请尝试.
If this does not work out then try this.
2) 在VCB中创建一个VCA实例,每当您从VCA移到VCB时,将VCA的值传递给VCB实例,然后从那里重新加载表.
2) create an instance of VCA in VCB and whenever you move from VCA to VCB pass the value of VCA to the instance of VCB and from there reload the table.
VCB
var instanceOfVCA:VCA! // Create an instance of VCA in VCB
func saveButton(){
instanceOfVCA.tableView.reloadData() // reload the table of VCA from the instance
dismiss(animated: true, completion: nil)
}
VCA
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
VCB.instanceOfVCA = self // Pass the value of VCA in instance of VCB while navigating through segue
}
这篇关于关闭viewController后重新加载tableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!