关闭模态回调

时间:2017-09-12 10:06:26

标签: ios swift

我有一个带有表格的视图,在每个表格单元格上我可以添加一些数据,所以我把它放在模态中,实际上是另一个视图。在我的模态中,我有这个代码

@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()
    }

这适用于简单的segue但不适用于modal,在这种情况下我应该使用什么?

4 个答案:

答案 0 :(得分:0)

可见副本:duplicate

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

protocol ModalDelegate {
    func didCloseModal();
}

在模态控制器类中,创建ModalDelegate协议的实例。并致电' delegate.didCloseModal()'在解雇之前

然后让您的父控制器实现ModalDelegate协议 并实现像didCloseModal

这样的函数viewDidAppear

答案 1 :(得分:0)

我猜你的viewDidAppear方法不会再被调用。尝试使用NsNotification通知你的第一个VC,如果上下文保存并重绘/刷新/重新加载...等你想要的。

答案 2 :(得分:0)

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

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()
}

答案 3 :(得分:0)

所以我以另一种方式做到了,我添加到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()
相关问题