iOS 13 swift設(shè)置狀態(tài)欄背景的顏色的bug

statusBar設(shè)置為單例,因?yàn)橛行┛刂破鞔嬖趯?dǎo)航存在透明狀態(tài)

iOS 13之前,可以通過(guò)valueForKey 獲取UIApplication的statusBar,因?yàn)閁IApplication是單例,因此,在iOS 12,通過(guò):?[[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"]拿到的statusBar永遠(yuǎn)是同一個(gè)對(duì)象。不行可以打印出內(nèi)存地址看下就很清楚了。iOS 13之后,因?yàn)樘O果不允許使用KVC的valueForKey訪問(wèn)私有屬性。通過(guò)上面的代碼可以多看點(diǎn),每次進(jìn)來(lái)都調(diào)用?alloc:init的方法,重新生成一個(gè)statusBar;然后添加到UIApplication的keyWindow上,再設(shè)置背景顏色。因此這個(gè)方法多次調(diào)用就會(huì)創(chuàng)建多份statusBar,造成內(nèi)存開銷不說(shuō),如果設(shè)置為透明,根部不能起開效果。

//狀態(tài)欄背景顏色設(shè)置

? ? func setStatusBarBackgroundColor(color : UIColor) {

? ? ? ? if #available(iOS 13.0, *) {

? ? ? ? ? ? if ???.statusBar == nil {//這個(gè)???代表當(dāng)前控制器,

? ? ? ? ? ? ? ? ???.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

? ? ? ? ? ? }

? ? ? ? }


? ? }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容