【问题标题】:Return control to function when modal viewcontroller dismissed模式视图控制器关闭时返回控制功能
【发布时间】:2018-07-16 17:56:37
【问题描述】:

我需要呈现一个模态 VC,它在呈现的 VC 中设置一个属性,然后我需要在呈现的 VC 中使用该值做一些事情。我必须能够将指向不同属性的指针传递给这个函数,以便它可以重用。我有下面的代码(KeyPickerTableViewController 是模态 VC)。

它应该可以工作,除非不是,因为present(picker... 之后的行会在选择器出现后立即执行。

如何让我的演示 VC “等待”直到模态 VC 被解除?

@objc func fromKeyTapped(_ button: UIBarButtonItem) {
    print("from tapped")
    setKey(for: &sourceKey, presentingFrom: button)
}

@objc func toKeyTapped(_ button: UIBarButtonItem) {
    print("from tapped")
    setKey(for: &destKey, presentingFrom: button)
}

fileprivate func setKey(for key: inout Key!, presentingFrom buttonItem: UIBarButtonItem) {
    let picker = KeyPickerTableViewController()
    picker.delegate = self
    picker.modalPresentationStyle = .popover
    picker.popoverPresentationController?.barButtonItem = buttonItem
    present(picker, animated: true, completion: nil)
    if let delKey = delegatedKey {
        key = delKey
    }
}

【问题讨论】:

  • 你在哪里设置这个值 delegatedKey ,如果你设置 picker.delegate = self 它应该你的VC里面有一个更新委托函数??

标签: swift


【解决方案1】:

您可以使用委托模式或闭包。

我会做以下事情 1.我不会使用inout模式,我会先调用popover,然后分别更新需要更新的内容 2. 在 KeyPickerTableViewController 中定义属性 var actionOnDismiss: (()->())?并在初始化 KeyPickerTableViewController 后将此操作设置为我们需要的操作

我可以在代码中显示它,但是您显示的摘要不够清楚,无法提出具体的修改。请参考下图。

import UIKit

class FirstVC: UIViewController {

    var key = 0

    @IBAction func buttonPressed(_ sender: Any) {
        let vc = SecondVC()
        vc.action = {
            print(self.key)
            self.key += 1
            print(self.key)
        }
        present(vc, animated: true, completion: nil)

    }

}

class SecondVC: UIViewController {
    var action: (()->())?

    override func viewDidLoad() {
        onDismiss()
    }

    func onDismiss() {
        action?()
    }
}

【讨论】:

  • 谢谢@Andrey,效果很好!然而,这让我将@escaping 添加到我的setKey 函数中,现在是setKey(presentingFrom buttonItem: UIBarButtonItem, with action: (@escaping ()->()))。我想您没有创建一个函数来执行您的示例中的操作,所以这可能符合您的预期。
  • 我认为没关系,转义闭包在执行之前一直保留在内存中,关于转义和非转义闭包的好材料 - medium.com/@kumarpramod017/…
【解决方案2】:

在呈现VC时,在其completion handler中添加dismissing modal VC action,以便在dismissal完成后呈现Viewcontroller

present(picker, animated: true, completion: { (action) in
   //dismissal action
   if let delKey = delegatedKey {
        key = delKey
   }
})

【讨论】:

  • 不是在模态vc出现时调用完成处理程序,而不是在它消失时调用吗?
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 2018-03-08
  • 2013-01-08
  • 2022-01-10
  • 1970-01-01
  • 2013-01-01
  • 1970-01-01
相关资源
最近更新 更多