美文网首页
iOS 13 swift设置状态栏背景的颜色的bug

iOS 13 swift设置状态栏背景的颜色的bug

作者: CSuiXin | 来源:发表于2020-03-18 11:28 被阅读0次

statusBar设置为单例,因为有些控制器存在导航存在透明状态

iOS 13之前,可以通过valueForKey 获取UIApplication的statusBar,因为UIApplication是单例,因此,在iOS 12,通过: [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"]拿到的statusBar永远是同一个对象。不行可以打印出内存地址看下就很清楚了。iOS 13之后,因为苹果不允许使用KVC的valueForKey访问私有属性。通过上面的代码可以多看点,每次进来都调用 alloc:init的方法,重新生成一个statusBar;然后添加到UIApplication的keyWindow上,再设置背景颜色。因此这个方法多次调用就会创建多份statusBar,造成内存开销不说,如果设置为透明,根部不能起开效果。

//状态栏背景颜色设置

    func setStatusBarBackgroundColor(color : UIColor) {

        if #available(iOS 13.0, *) {

            if ???.statusBar == nil {//这个???代表当前控制器,

                ???.statusBar = UIView.init(frame: (UIApplication.shared.keyWindow?.windowScene?.statusBarManager!.statusBarFrame)!)

                ???.statusBar!.backgroundColor = color

                UIApplication.shared.keyWindow?.addSubview(???.statusBar!)

            }else{

               ???.statusBar!.backgroundColor = color

            }

        }else{

            // Fallback on earlier versions

            let statusBarWindow : UIView = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView

            letstatusBar :UIView= statusBarWindow.value(forKey:"statusBar")as!UIView

            if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {

                statusBar.backgroundColor= color

            }

        }

    }

相关文章