【问题标题】:Display UIView Above Apple Status Bar in iOS 8在 iOS 8 中在 Apple 状态栏上方显示 UIView
【发布时间】:2014-11-06 14:25:23
【问题描述】:

我知道已经发布了一些关于此的问题,但没有一个对我的具体问题有帮助。我想在整个屏幕上方显示一个自定义模式,但我想保持 Apple 状态栏可见。对于模态,我使用一个UIView 用于调光效果,另一个用于用户将与之交互的实际视图。然后将整个模态框作为子视图添加到当前视图并放在前面。本质上,我试图复制 UIAlertView 的行为,但自定义视图除外。这是我的一些代码:

var modalView:UIView = UIView(frame: self.view.window!.bounds)
modalView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.66)
modalView.addSubview(customView)    

self.view.window!.addSubview(modalView)
modalView.window!.windowLevel = UIWindowLevelStatusBar + 1

self.bringSubviewToFront(modalView)

以上,customView 是用户与之交互的UIView

这很好用,但出于某种原因,即使状态栏的样式设置为 LightContent,Apple 状态栏上的文本也会消失。从代码中可以看出,我没有触摸状态栏。

我正在尝试使状态栏上的文本变暗,就像屏幕的其余部分一样,目前卡住了。有人对我如何获得所需的行为有任何见解吗?

任何帮助将不胜感激!

【问题讨论】:

标签: ios swift screen statusbar


【解决方案1】:

2017 年 12 月更新 • Swift 4 • iOS 10.0+

我简单地尝试了接受答案的编辑解决方案,但我无法轻松地为 UIView 横幅制作整个 viewController。但是,通过访问UIApplication 中的statusBar 值,我能够将UIView 作为子视图添加到statusBarView这会将 UIView 放在状态栏的顶部。据我所知,这是一个相对稳定的解决方法,适用于最近的几个 iOS 版本。

extension UIApplication {

    /// Returns the status bar UIView
    var statusBarView: UIView? {
        return value(forKey: "statusBar") as? UIView
    }

}

用法

let customBannerView = CustomStatusView(with: message)
UIApplication.shared.statusBarView?.addSubview(customBannerView)

【讨论】:

  • 我认为这不是一个好方法,因为您正在尝试访问您不应该访问的私有视图。这种方法在 iOS 11 中效果很好,但在 iOS 9 中效果不佳,例如,您必须在访问 statusBarView 之前访问 statusBarWindow。我不会这样做。
【解决方案2】:

编辑(2015 年 11 月 16 日)

我正在从下面的this 线程复制我的答案:

这个答案在 iOS 8.3+ 和可能的 iOS 8 以前的版本中中断。我不建议任何人使用它,特别是因为不能保证它在未来的 iOS 版本中有效。

我的新解决方案使用UIViewController 的标准presentViewController 方法。我初始化了一个UIViewController,将我的自定义模态View 添加为UIViewController 的子视图,然后可以选择使用约束定位模态View。像魅力一样工作!


原答案

按照 Anna 的建议,我通过使用 UIWindow 而不是 UIView. 让它工作了这是我的新代码:

var modalWindow:UIWindow = UIWindow(frame: self.view.window!.bounds)

modalWindow.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.66)
modalWindow.hidden = false
modalWindow.windowLevel = (UIWindowLevelStatusBar + 1)

modalWindow.addSubview(customView)    

modalWindow.makeKeyAndVisible()

它现在和以前一样工作,除了 Apple 状态栏上的文本也变暗了。非常感谢大家的帮助!

【讨论】:

  • 简单说明:要隐藏窗口,请将modalWindow 设置为nil,如下所示:modalWindow = nil
  • 您是否设法处理了这个临时 uiwindow 的旋转?请检查我的问题stackoverflow.com/questions/26976494/…
  • 嗨@žhecownyakh,我不推荐这个解决方案,即使它可以在iOS 9中运行。将UIWindows用于模式的问题是它们在不同版本的iOS中工作方式不同.在某些版本中,它们仅处于纵向模式,而在其他版本中则不是。这使得该解决方案不可预测,并且在未来容易被破坏。我会在这里推荐我的新答案,使用标准 API:stackoverflow.com/questions/26916009/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
  • 2014-01-14
相关资源
最近更新 更多