iOS-更改状态栏背景和文字颜色(OC + Swift3)

更改状态栏背景使用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
        }
    }
}

使其达到如下运行效果:
这里写图片描述

参考:http://www.jianshu.com/p/5c09c2700038

源代码Demo: https://github.com/qxuewei/XWCSDNDemos/tree/master/StatusBarDemo%E7%8A%B6%E6%80%81%E6%A0%8F%E7%9B%B8%E5%85%B3

猜你喜欢

转载自blog.csdn.net/qiuxuewei2012/article/details/53763653