弹出窗口有黑色背景,即使它设置为清除

Popup has black background even though it is set to clear

我有一个 UIViewController 正在展示另一个。它应该显示为具有透明背景的弹出窗口。正常显示,但背景是黑色的。它在嵌入 UINavigationController 时显示。

问题是背景颜色是黑色,我看不到下面的视图,即使所有背景颜色都设置为清除。我什至尝试在呈现控制器时将背景设置为清晰,但仍然没有。我在 Storyboard 中设置它以显示当前上下文和交叉溶解。

视图调试器也不会在层次结构中将任何视图显示为黑色。不知道哪里出了问题,感谢任何帮助,谢谢!

let vc = UIStoryboard.init(name: "AccountSettings", bundle: nil).instantiateViewController(withIdentifier: "upgradeVCPopup") as! UpgradeVCPopup
let nav = UINavigationController(rootViewController: vc)
nav.view.backgroundColor = .clear
vc.view.backgroundColor = .clear
if let navigationController = self.navigationController {
    navigationController.present(nav, animated: true, completion: nil)
} else {
    self.present(nav, animated: true, completion: nil)
}

你有黑色背景的原因是你没有设置你的 UIViewControllers UIModalPresentationStyle。此参数确定您的模态视图控制器如何显示。模态视图控制器的默认值是 fullScreen.

来自Apple Documentation

UIModalPresentationStyle.fullScreen

The views belonging to the presenting view controller are removed after the presentation completes.

这意味着在你的view controller被呈现之后,之前的view controller被移除了。当它被移除时,因为它下面没有任何东西,你会看到黑色。如果您希望以前的视图控制器保留并可见,您可以将 modalPresentationStyle 设置为 overFullScreen

来自Apple Documentation

UIModalPresentationStyle.overFullScreen

The views beneath the presented content are not removed from the view hierarchy when the presentation finishes. So if the presented view controller does not fill the screen with opaque content, the underlying content shows through.

为此,请在呈现视图控制器之前添加以下行:

vc.modalPresentationStyle = .overFullScreen

这应该有所帮助。

您是否尝试过设置 nav.view.backgroundColor = .white 通过设置 nav.view.backgroundColor = .clear 您正在将导航 window 的背景设置为清除(导航 window 的默认基础是黑色)