更改状态栏背景使用runtime和KVC直接修改,文字颜色直接使用属性修改
OC版本:
//
// ViewController.m
// StatusBarDemo
//
// Created by 邱学伟 on 2016/12/20.
// Copyright © 2016年 邱学伟. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
[self setStatusBarBackgroundColor:[UIColor greenColor]];
}
//设置状态栏背景颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
statusBar.backgroundColor = color;
}
}
//状态栏文字颜色 此方法直接添加在需要更改的控制器上即可,无需调用
- (UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
@end
Swfit版本:
第一步在info.plist 加上这个View controller-based status bar appearance = NO
第二步:
//
// ViewController.swift
// StatusBarDemoSwift
//
// Created by 邱学伟 on 2016/12/20.
// Copyright © 2016年 邱学伟. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.green
setStatusBarBackgroundColor(color: .green)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.statusBarStyle = .lightContent
}
///设置状态栏背景颜色
func setStatusBarBackgroundColor(color : UIColor) {
let statusBarWindow : UIView = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView
let statusBar : UIView = statusBarWindow.value(forKey: "statusBar") as! UIView
/*
if statusBar.responds(to:Selector("setBackgroundColor:")) {
statusBar.backgroundColor = color
}*/
if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
statusBar.backgroundColor = color
}
}
}
使其达到如下运行效果: