【问题标题】:How to access my custom UIPresentationController from within presented controller?如何从呈现的控制器中访问我的自定义 UIPresentationController?
【发布时间】:2018-01-01 13:13:42
【问题描述】:

这就是我执行转换的方式:

extension UIViewController: UIViewControllerTransitioningDelegate {

    public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return OverlayPresentationController(presentedViewController: presented, presenting: presenting)
    }

    func presentOverlayController(_ controller: UIViewController) {

        controller.modalPresentationStyle = .custom
        controller.transitioningDelegate = self

        present(controller, animated: true)
    }
} 

然后在我呈现的控制器 (AlertVC) 中,有时我需要访问它的呈现控制器:

print(presentationController as? OverlayPresentationController) //nil
print(presentationController) //is ok, UIPresentationController

为什么?

介绍:

let controller = AlertVC.instantiate()
controller.update()
presentOverlayController(controller)

class AlertVC: UIViewController {

    class func instantiate() -> AlertVC {
        return UIStoryboard(name: "Alert", bundle: Bundle(for: LoginVC.classForCoder())).instantiateInitialViewController() as! AlertVC
    }

    func update() {
        _ = view

        print(presentationController as? OverlayPresentationController) //nil
    }
}

【问题讨论】:

  • UIPresentationController 有一个名为 containerView 的属性。它保存了展示和展示的控制器的视图层次结构
  • 听起来很有希望...可以通过这种方式访问​​我的演示控制器吗?
  • 对不起,我不知道,我已经通过互联网阅读了它,所以我与您分享,您可以尝试如果有效,那么您的大量时间将被节省。祝你好运

标签: ios swift uipresentationcontroller


【解决方案1】:

你可以通过调用presentingViewController得到当前视图控制器的视图控制器

// The view controller that presented this view controller (or its farthest ancestor.)
self.presentingViewController 

如果您的呈现视图控制器位于返回 UINavigationController 的导航控制器中。你可以像这样得到你需要的视图控制器:

let presentingNVC = self.presentingViewController as? UINavigationViewController
let neededVC = presentingNVC.viewControllers.last as? NeededViewController

【讨论】:

  • @BartłomiejSemańczyk 你在哪里尝试打电话给presentingViewController?如果您尝试在viewDidLoad: 中调用它,则该值可能尚未设置。
  • @BartłomiejSemańczyk 你确定你是在使用present(controller, animated: true) 呈现的视图控制器中调用它吗?
  • @BartłomiejSemańczyk 我认为您在presentationController(forPresented:presenting:source:) 的返回语句上方缺少presentationController.delegate = self
  • @BartłomiejSemańczyk 你能把你的初始化代码添加到问题中吗?
猜你喜欢
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 2018-02-13
  • 2012-11-20
相关资源
最近更新 更多