且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

【iOS开发】修改 present 出来的 ViewController 状态栏颜色

更新时间:2022-10-09 18:56:58

在开发的过程中,如果我们需要给用户提供一个浏览器功能的支持、又或者需要让用户来从系统相册挑选图片,那么利用 UIKit 给我们提供的现成的 SFSafariViewController 和 UIImagePickerController 将是非常方便的事情,但是

    let pc = UIImagePickerController()
    let sf = SFSafariViewController(URL: NSURL(string:""))

像这样用一行代码来创建 ViewController,使我们丧失了进入这个 ViewController 的内部去调节一些东西的机会。

比如说我们整个App都是采用的白色状态栏,而 SFSafariViewController 和 UIImagePickerController 都是默认背景为白色的(即需要一个黑色状态栏,否则用户看不清内容),这时候我们需要一个默认自身的状态栏永远为黑色的 SFSafariViewController 或 UIImagePickerController

下面以 UIImagePickerController 为例给出一种解决方案。

class CustomImagePC: UIImagePickerController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func viewWillDisappear(animated: Bool) {
        UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
    }
    
}

如上所示,创建了一个自定义的 UIImagePickerController ,代码里面设定了:这个页面被加载之后,状态栏设置为黑色,页面即将消失时,状态栏再转为白色。调用的时候,直接

    let pc = CustomImagePC() 

SFSafariViewController 同理,当然你也可以在这些代码里插入其他内容,如果你想更高程序地定制一个 UIImagePickerController 的话。