如何检查最顶层的视图控制器是否是 ImagePickerController

How to check if the top most view controller is an ImagePickerController

我使用 following 检查最顶层的视图控制器。我需要检查顶视图控制器是否是 ImagePickerController

guard let window = UIApplication.shared.windows.first(where: \.isKeyWindow) else { return }
        
guard let topVC = window.topViewController() else { return }

if topVC.isKind(of: ImagePickerController.self) {
    // ...
}

但我得到一个错误

如何检查顶部 vc has/is 图像选择器是否显示?

extension UIWindow {
    func topViewController() -> UIViewController? {
        var top = self.rootViewController
        while true {
            if let presented = top?.presentedViewController {
                top = presented
            } else if let nav = top as? UINavigationController {
                top = nav.visibleViewController
            } else if let tab = top as? UITabBarController {
                top = tab.selectedViewController
            } else {
                break
            }
        }
        return top
    }
}

您正在设置 ImagePickerController.self 但 class 名称是 UIImagePickerController

你可以这样使用

if let imagePicker = UIApplication.shared.windows.first?.topViewController() as? UIImagePickerController {
 // Do your stuf
}

if topVC.isKind(of: UIImagePickerController.self) {
    // ...
}

注意:通过使用它你不能将顶视图控制器转换为UIImagePickerController。因为它是由苹果设计的。

您可以使用它并通过它访问视图控制器。

if let pickerHostClass = NSClassFromString("PUPhotoPickerHostViewController"), topVC.isKind(of: pickerHostClass) {
   topVC.view.alpha = 0.5
}