Swift/iOS13 - 从自定义类中调用UIApplication.shared.delegate.window?.rootViewController?.present()

5

我在Xcode11中创建了一个新的故事板项目,并试图从自定义类中呈现一个ViewController,方法如下(在旧项目中可以正常工作):

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : UIViewController = storyboard.instantiateViewController(withIdentifier: "NotificationVC") as UIViewController
appDelegate.window?.makeKeyAndVisible()
appDelegate.window?.rootViewController?.present(vc, animated: true, completion: nil)

当然,现在这个代码不起作用了,因为AppDelegate中没有window变量了,它已经被移动到SceneDelegate中。
错误信息:'AppDelegate'类型的值没有'member window'
如何使这段代码现在能够工作?
我想做什么:
当用户点击推送通知托盘时,我想展示一个视图控制器。
编辑:目前,我通过在SceneDelegate中创建一个私有静态变量,并在我的自定义类中访问该变量,使其能够工作。
SceneDelegate.swift
private(set) static var shared: SceneDelegate?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    guard let _ = (scene as? UIWindowScene) else { return }
    Self.shared = self
}

CustomClass.swift

let sceneDeleage = SceneDelegate.shared
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : UIViewController = storyboard.instantiateViewController(withIdentifier: "NotificationVC") as UIViewController
sceneDeleage?.window?.makeKeyAndVisible()
sceneDeleage?.window?.rootViewController?.present(vc, animated: true, completion: nil)

这可能不被推荐,如此在这里声明:https://dev59.com/0lMH5IYBdhLWcg3wuxw-#58547992,但它可以工作。

编辑2:这是我的另一个解决方案,感谢https://dev59.com/Z7fna4cB1Zd3GeqPmx0l#58557634

    let window = UIApplication.shared.windows.first
    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vc : UIViewController = storyboard.instantiateViewController(withIdentifier: "NotificationVC") as UIViewController
    window?.makeKeyAndVisible()
    window?.rootViewController = vc

如果有人找到更好的解决方案,请分享。


1
请检查您的应用程序委托文件,看看是否有 var window: UIWindow? - Prashant Tukadiya
自从新的xcode11项目中出现了scenedelegate中的windows变量,所以它不在那里。如果我将其添加到appdelegate中,我的代码就什么也不做,因为它是nil,如果我强制解包window!,我会得到“致命错误:意外地发现nil值”。 - kironet
这实际上不是重复的问题,我只是不想在一个问题中问两个问题。那里的答案在 ViewController 中可以正常工作。但我无法在自定义类中实现它。 - kironet
使用UIApplication.shared.windows属性获取应用程序窗口。请参考https://developer.apple.com/documentation/uikit/uiapplication/1623104-windows - Apparao Mulpuri
1个回答

2

2
使用 UIApplication.shared.windows 如何解决这个问题?一个应用程序可以有多个场景。通过迭代应用程序窗口,自定义类如何知道哪个窗口是正确的窗口? - rmaddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接