SFSafariViewController 状态栏样式

17

我的应用程序的状态栏样式是UIStatusBarStyleLightContent,并且它在根视图控制器中设置为preferredStatusBarStyle

现在我有一个问题,当从我的应用程序中打开SFSafariViewController时,它继承了状态栏样式,该状态栏样式为浅色并且在SFSafariViewController的白色背景上不可见。

是否有一种方法可以为SFSafariViewController设置状态栏样式?

P.S. 我尝试创建SFSafariViewController的子类并覆盖此方法,但它没有帮助。

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

更新:

[[UIApplication sharedApplication] setStatusBarStyle:]可以解决问题,但此方法在iOS 9中已被弃用。


似乎这个问题出现是因为我在info.plist中没有将uiviewcontroller-based status bar appearance键设置为YES。我重写了状态栏样式代码,使用了基于视图控制器的方式,现在一切都运行得非常完美。 - Alexander Tkachenko
@ClayEllis 抱歉,当时错过了。感谢您的回答。 - Alexander Tkachenko
4个回答

27

你根本不需要子类化 SFSafariViewController

只需在你的 SFSafariViewController 实例上设置 modalPresentationCapturesStatusBarAppearance = true,它就会自行处理剩下的事情。

这是因为其默认的 preferredStatusBarStyle.default。视图层次仍然依赖于呈现视图控制器的状态栏外观,因此通过将 modalPresentationCapturesStatusBarAppearance 设置为 true,它将成为被请求状态栏外观的接收者。

简而言之

safariViewController.modalPresentationCapturesStatusBarAppearance = true

当在您的 Info.plist 中将 UIViewControllerBasedStatusBarAppearance 设置为 NO 时,此行为将被覆盖并且不起作用。


1
感谢您提供最优雅的解决方案。 - Alexander Tkachenko
@Alex,你能否解释一下为什么它没有生效?根据Clay的信息,SafariVC应该是设置状态栏文本颜色的那个。我刚试了一下,它对我有效。 - micnguyen
1
提醒一下,如果你的信息列表中的属性键"UIViewControllerBasedStatusBarAppearance"设置为NO,这个方法是不起作用的。 - Pochi

9

这不是最佳方案,但是它可以实现。

class MySafariViewContoller: SFSafariViewController {

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)

        UIApplication.sharedApplication().statusBarStyle = .Default
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillAppear(false)

        UIApplication.sharedApplication().statusBarStyle = .LightContent
    }
}

根据您的喜好更改 .Default 和 .LightContent。


不错的解决方案,可以让应用程序的最低iOS版本保持在8.0,并且仍然(如果用户使用的是9.0)使用继承自SFSafariViewController的类吗? - Thomas Besnehard
我找到答案了 @available(iOS 9.0, *) class 我的Safari视图控制器: SFSafariViewController - Thomas Besnehard
UIModalPresentationStyle属性设置为fullScreen时,此解决方案有效,否则请使用上面@clay-ellis接受的答案。 - yohannes

8
您可以使用扩展功能。
extension SFSafariViewController {

    override open func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        UIApplication.shared.statusBarStyle = .default
    }

    override open func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        UIApplication.shared.statusBarStyle = .lightContent
    }

}

我该如何在Objective-C中实现这个? - CyberMew

1

这怎么样?

class MyCustomSafariViewController: SFSafariViewController {

    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
}

或者私有API - 如果您可以使用它。

谢谢你的建议,但我想要暗色状态栏样式。已更新答案,尝试了子类化,但没有起作用。不能使用私有API。 - Alexander Tkachenko
返回 .Default 并不起作用,实际上 preferredStatusBarStyle 从未被调用。 - Luca Torella
12
不建议使用私有API。 - Simon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接