关闭模态回调



我有一个带有表的视图,在每个表单元格上,我都可以添加一些数据,因此我将其放入Modal中,这实际上是另一种视图。在我的模式中,我有此代码

@IBAction func closeModal(_ sender: Any) {
        if let amountVal = amount.text {
            if let amountInt = Int16(amountVal) {
                let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
                let activity = Activity(context: context)
                activity.created_at = Date() as NSDate
                activity.amount = amountInt
                countedObject?.addToActivities(activity)
                do {
                    try context.save()
                    navigationController?.popViewController(animated: true)
                } catch let error {
                    NSLog(error.localizedDescription)
                }
            }
        }

        dismiss(animated: true, completion: nil)
    }

因此,我更新了核心数据实体和关闭模式,但是关闭模式后,第一个视图没有更新,因此直到重新启动模拟器之前,它才反映我所做的更改。在我的第一个观点中,我有这个

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func viewDidAppear(_ animated: Bool) {
        populateCountObjects()
    }

这适用于简单的细分,但对模态不起作用,在这种情况下我应该使用什么?

所以我以另一种方式做到了,我添加了viewController

static var sharedInstace : ViewController?
override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        ViewController.sharedInstace = self
    }

在解雇方法之后的模态中

ViewController.sharedInstace?.didCloseModal()

popible重复:重复

您需要使用专用方法的委托

protocol ModalDelegate {
    func didCloseModal();
}

在您的模态控制器类中,创建一个modaldelegate协议的实例。并在解雇之前调用' delegate.didCloseModal()'

然后使您的父控制器实现ModalDelegate协议并实现函数didCloseModal,例如viewDidAppear

让系统为您完成工作。在这种情况下,您会在保存上下文时收到通知。

override func viewDidLoad() {
    super.viewDidLoad()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let center = NotificationCenter.default
    center.addObserver(self, selector: #selector(contextDidSave(_:)), name: .NSManagedObjectContextDidSave, object: context)
}
func contextDidSave(_ notification: Notification) {
    populateCountObjects()
}

如果这对您不起作用,则每当更改对象时,您总是可以降低并获得通知。

override func viewDidLoad() {
    super.viewDidLoad()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let center = NotificationCenter.default
    center.addObserver(self, selector: #selector(contextObjectsDidChange(_:)), name: .NSManagedObjectContextObjectsDidChange, object: context)
}
func contextObjectsDidChange(_ notification: Notification) {
    populateCountObjects()
}

我想您的viewDidAppear方法不会再次调用。尝试使用NsNotification如果保存的上下文并重新刷新/重新加载...

最新更新