iOS在任何地方都能显示ViewController

在开发的时候,有很多地方需要显示UIViewController,但在很多时候很不方便显示,比如在一个不是ViewController的类里在一个普通的View里或者一个管理类里,在这些情况下我们需要将源ViewController传递到使用的地方使用如下方式显示VC:

viewController.present(vc, animated: animated, completion: completion)

从以上代码可以看出来,如果在一个比较深层嵌套的View中要显示ViewController要不把源ViewController传递到这个View中要不就是做代理,将要做的操作传递到源ViewController中,很明显这两种写法都很繁杂,一层套一层很容易出问题,那么有没有方法可以解决这个问题呢,答案是肯定的,写法去下:

extension UIViewController {
    public func showViewController(_ animated:Bool,completion: (() -> Void)?) {
        let popWindow = UIWindow(frame:UIScreen.main.bounds)
        popWindow.rootViewController = UIViewController()
        popWindow.backgroundColor = UIColor.clear
        popWindow.rootViewController?.view.backgroundColor = UIColor.clear
        popWindow.windowLevel = UIWindowLevelAlert
        popWindow.makeKeyAndVisible()
        popWindow.rootViewController?.present(self, animated: animated, completion: completion)
    }
}

我们只需在程序中添加这个UIViewController的扩展方法,然后使用方法就是将需要显示的ViewController直接调用这个方法即可。

不过需要注意的是这中方式是通过创建新的window来显示的,不知道在特殊的情况下会不会有问题,如果大家遇到问题可以联系我我会及时回复。

0 0 投票数
文章评分
订阅评论
提醒
guest
0 评论
内联反馈
查看所有评论
京ICP备17066706号-1
0
希望看到您的想法,请您发表评论x