ios - 添加叠加层以覆盖整个屏幕(包括状态栏)

标签 ios swift

我有一个叠加层 (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)

最佳答案

经过评论的讨论发现改变statusBarbackgroundColor是你的代码不能正常工作的原因。

通过打印 statusBarsuperView 我发现 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 颜色。您可以将其样式设置为 defaultlight

关于ios - 添加叠加层以覆盖整个屏幕(包括状态栏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49689536/

相关文章:

ios - 将条形按钮项目设置为导航 Controller 上的后退按钮

ios - 无需键即可访问 NSMutableDictionary 值?

ios - 将我的 iPhone 用作开发设备会破坏我的 iPhone 正常使用吗?

ios - 使用 SwiftUI 创建手势来编辑列表项

swift - 如何使用 swift 为不透明度设置动画?

ios - 用户输入的 f(x) 可在 swift 中使用

ios - 3D触摸力有单位吗?

objective-c - ios 中的 UIButton AddTarget(不工作-崩溃)

xcode - 为什么我必须将库嵌入到应用程序二进制文件中才能正常工作?

ios - subview 加载但没有一个按钮可以工作 ios swift