简体   繁体   English

XCode 预览错误:“替换了 'keyWindow' 的访问器”

[英]XCode Preview Error: "Replaced Accessor for 'keyWindow'"

Adding the some code to one of my files in XCode causes the following error to show when trying to run previews for that file:在 XCode 中将一些代码添加到我的文件之一会导致在尝试运行该文件的预览时显示以下错误:

Compiling failed: replaced accessor for 'keyWindow' occurs in multiple places.

The error only happens when the following code is used in the file:该错误仅在文件中使用以下代码时发生:

extension UIApplication {
    
    var keyWindow: UIWindow? {
        return UIApplication.shared.connectedScenes
            .filter { $0.activationState == .foregroundActive }
            .first(where: { $0 is UIWindowScene })
            .flatMap({ $0 as? UIWindowScene })?.windows
            .first(where: \.isKeyWindow)
    }
    
    var keyWindowPresentedController: UIViewController? {
        var viewController = self.keyWindow?.rootViewController
        
        if let presentedController = viewController as? UITabBarController {
            viewController = presentedController.selectedViewController
        }
        
        while let presentedController = viewController?.presentedViewController {
            if let presentedController = presentedController as? UITabBarController {
                viewController = presentedController.selectedViewController
            } else {
                viewController = presentedController
            }
        }
        return viewController
    }
}

I know very little about UIKit, and this code was copy/pasted from online.我对 UIKit 知之甚少,这段代码是从网上复制/粘贴的。 Why is this code crashing my preview, and how can I fix it?为什么此代码会使我的预览崩溃,我该如何解决?

I'm running XCode 13.4.1 on macOS Monterey我在 macOS Monterey 上运行 XCode 13.4.1

UIApplication already has keyWindow property and it seems there is already other extension with same property in workspace, so just use different name for your, like UIApplication已经具有keyWindow属性,并且似乎在工作区中已经存在具有相同属性的其他扩展,因此只需为您使用不同的名称,例如

extension UIApplication {
    
    var currentWindow: UIWindow? {

*or find which one another is and see if you can reuse it. *或者找出另一个是,看看你是否可以重复使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM