我有 2 个 ViewController:
VC1 根据 CoreData 属性 isPicked 填充其 tableView,该属性为 bool,仅显示具有 true
状态的项目。 VC2 是第二个模态(非全屏) View Controller ,允许用户更改 isPicked 属性的状态:选中和取消选中项目(使其为 true 或 false),按下“保存”按钮后,更改将被保存保存在 CoreData 中,VC2 将被忽略。但是,VC1 不会使用来自 VC2 的最新更改进行 self 更新。
我尝试过的:
- 加载我的数组以在 viewWillAppear() 中的 VC1 中显示,但由于我的 VC2 是模态视图而不是全屏,因此该方法仅调用一次
- 尝试实现协议(protocol)和委托(delegate),但结果是相同的 - 无法重新加载数据(但假设我可能做错了)
我的 VC1:
override func viewDidLoad() {
super.viewDidLoad()
let predicate = NSPredicate(format: "isPicked == YES")
converterArray = load(for: tableView, and: predicate)
}
func load(for tableView: UITableView, with request: NSFetchRequest<Currency> = Currency.fetchRequest(), and predicate: NSPredicate? = nil, sortDescriptor: [NSSortDescriptor] = [NSSortDescriptor(key: "shortName", ascending: true)]) -> [Currency] {
var array = [Currency]()
request.predicate = predicate
request.sortDescriptors = sortDescriptor
do {
array = try context.fetch(request)
} catch {
print(error)
}
DispatchQueue.main.async {
tableView.reloadData()
}
return array
}
我的 VC2:
@IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
do {
try context.save()
} catch {
print(error)
}
dismiss(animated: true)
}
另外请看一个简短的 GIF,我展示了发生的情况:CLICK
我不知道 VC2 关闭后如何自动更新 VC1 中的更改...
最佳答案
我假设数据已正确保存在 VC2 中,您遇到的唯一问题是在 VC1 中重新加载数据的正确方法。
使 VC1 符合 UIViewControllerTransitioningDelegate
并实现其委托(delegate)函数 animationController(forDismissed Dismissed: UIViewController)
可能会解决您的问题
了解更多 here
试试这个
// Some function in VC1 which loads VC2
func loadVC2()
{
let newVC = UIViewController()
// This is important
newVC.transitioningDelegate = self
present(newVC, animated: true, completion: nil)
}
然后在VC1中,实现函数animationController(forDismissed Dismissed: UIViewController)
extension VC1: UIViewControllerTransitioningDelegate
{
// UIViewControllerTransitioningDelegate delegate function auto invoked during modal transitions
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
print("returned back")
// reload your table in VC1 here
/// Returning nil as per guidelines
return nil
}
}
尝试一下,看看是否可以解决您的问题。
关于swift - 当模态视图(第二个 VC)关闭时刷新 ViewController 中的核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70822224/