【问题标题】:How to hide the status bar when presenting a UIAlertController in a non-UIViewController class?在非 UIViewController 类中呈现 UIAlertController 时如何隐藏状态栏?
【发布时间】:2017-12-21 05:57:49
【问题描述】:

当用户点击非 UIViewController 类中的按钮时,我试图隐藏状态栏,但没有成功。

我正在使用以下代码来呈现UIAlertController

public extension UIAlertController
{
    func show()
    {
        let win = UIWindow(frame: UIScreen.main.bounds)
        let vc = UIViewController()
        vc.view.backgroundColor = .clear
        win.rootViewController = vc
        win.windowLevel = UIWindowLevelAlert + 1
        win.makeKeyAndVisible()    
        vc.present(self, animated: true, completion: nil)
    }
}

jazzgil 引用了以下答案:

ios - present UIAlertController on top of everything regardless of the view hierarchy

在我的UIButton 操作中,我实现了以下内容:

@IBAction func setImage(_ sender: UIBarButtonItem)
{
    let alertView = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.alert)

    // Create the alert's action button
    let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction!) in



    })

    let cancelAction = UIAlertAction(title: "CANCEL", style: .destructive, handler: nil)

    alertView.addAction(okAction)
    alertView.addAction(cancelAction)

    alertView.show()
}

我尝试在扩展中添加以下功能:

override open var prefersStatusBarHidden: Bool
{
    return true
}

然后设置alertView.modalPresentationCapturesStatusBarAppearance = truealertView.setNeedsStatusBarAppearanceUpdate() 但状态栏似乎总是出现。

有人可以指导我正确的方向吗?

谢谢!

【问题讨论】:

    标签: ios swift uialertcontroller


    【解决方案1】:

    希望对您有所帮助。

    要隐藏状态栏调用此方法(在您的情况下,在呈现 alertview 控制器之前)

    func hideStatusBar() {
         UIApplication.shared.keyWindow?.windowLevel = UIWindowLevelStatusBar
    }
    

    并返回状态栏调用此方法(关闭 alertview 控制器后)

    func updateStatusBarToPreviousState() {
         UIApplication.shared.keyWindow?.windowLevel = UIWindowLevelNormal
     }
    

    【讨论】:

    • 请解释答案和使用方法
    • 只需调用方法hideStatusBar 来隐藏状态栏并在关闭alertview 控制器后显示返回调用方法updateStatusBarToPreviousState
    • hideStatusBar 有效,但是当我在我的 okAction 中调用 updateStatusBarToPreviousState 时,状态栏永远不会重新出现??
    猜你喜欢
    • 1970-01-01
    • 2014-02-07
    • 2016-08-11
    • 1970-01-01
    • 2018-05-01
    • 2020-10-01
    • 2016-02-15
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多