我有一个叠加层 (UIImageView)
,它应该具有透明背景和 alpha。如何设置 imageview
使其覆盖整个屏幕?目前,它覆盖屏幕但不覆盖 UIStatusBar
。我在 AppDelegate 的
主 window
中添加 View 作为 subview
。
代码:
let overlay1 = UIImageView(image: UIImage(named: "overlay-image"))
overlay1.contentMode = .scaleAspectFit
overlay1.backgroundColor = UIColor.black
overlay1.alpha = 0.87
overlay1.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
overlay1.isUserInteractionEnabled = true
overlay1.layer.zPosition = 1
(UIApplication.shared.delegate as? AppDelegate).window.addSubview(overlay1)
最佳答案
经过评论的讨论发现改变statusBar
的backgroundColor
是你的代码不能正常工作的原因。
通过打印 statusBar
的 superView
我发现 statusBar
没有添加到 UIWindow
上,而是打开了UIStatusBarWindow
可能位于 mainWindow
之上。
另外请不要用力展开它可能会导致崩溃。最后我放了一个 guard
来获取 statusBar
,检查它是否响应 backgroundColor
属性,以获取它的 superView
并在此 superView
上添加覆盖使其正常工作。
您对 respondToSelector
的检查也是错误的。请参阅下面的代码,它根据您的要求工作。
guard let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView, statusBar.responds(to: NSSelectorFromString("backgroundColor")), let superView = statusBar.superview else {return}
statusBar.backgroundColor = UIColor.red
let overlay1 = UIImageView(image: UIImage(named: "overlay-image"))
overlay1.contentMode = .scaleAspectFit
overlay1.backgroundColor = UIColor.black
overlay1.alpha = 0.87
overlay1.frame = superView.bounds
overlay1.isUserInteractionEnabled = true
overlay1.layer.zPosition = 1
superView.addSubview(overlay1)
注意:不建议更改 statusBar
颜色。您可以将其样式设置为 default
或 light
。
关于ios - 添加叠加层以覆盖整个屏幕(包括状态栏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49689536/