如何在iOS 7上更改状态栏背景颜色和文本颜色?

时间:2013-09-28 04:42:28

标签: ios ios7 uicolor ios-statusbar

我当前的应用程序在iOS 5和6上运行。

导航栏为橙色,状态栏为黑色背景色,白色为文本颜色。但是,当我在iOS 7上运行相同的应用程序时,我发现状态栏看起来是透明的,具有与导航栏相同的橙色背景颜色,状态栏文本颜色为黑色。

由于这个原因,我无法区分状态栏和导航栏。

如何使状态栏看起来与iOS 5和6中的状态相同,即黑色背景颜色和白色文本颜色?我该如何以编程方式执行此操作?

24 个答案:

答案 0 :(得分:170)

我不得不尝试寻找其他方法。这不涉及addSubview窗口。因为当键盘出现时我正在向上移动窗口。

目标C

- (void)setStatusBarBackgroundColor:(UIColor *)color {

    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

夫特

func setStatusBarBackgroundColor(color: UIColor) {

    guard  let statusBar = UIApplication.sharedApplication().valueForKey("statusBarWindow")?.valueForKey("statusBar") as? UIView else {
        return
    }

    statusBar.backgroundColor = color
}

Swift 3

func setStatusBarBackgroundColor(color: UIColor) {

    guard let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView else { return }

    statusBar.backgroundColor = color
}

调用此表单application:didFinishLaunchingWithOptions为我工作。

N.B。我们在应用程序商店中有一个具有此逻辑的应用程序。所以我想应用商店政策是可以的。

修改

使用风险自负。组成评论者@Sebyddd

  

我有一个应用程序被拒绝的原因,而另一个被接受了   精细。他们确实将其视为私有API使用,因此您需要遵守   在审查过程中运气:) - Sebyddd

答案 1 :(得分:106)

转到您的应用info.plist

1)将View controller-based status bar appearance设为NO
2)将Status bar style设为UIStatusBarStyleLightContent

然后转到您的应用程序委托并将以下代码粘贴到您设置Windows的RootViewController。

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
    view.backgroundColor=[UIColor blackColor];
    [self.window.rootViewController.view addSubview:view];
}

希望它有所帮助。

答案 2 :(得分:27)

1)在plist中将UIViewControllerBasedStatusBarAppearance设置为YES

2)在viewDidLoad中执行[self setNeedsStatusBarAppearanceUpdate];

3)添加以下方法:

 -(UIStatusBarStyle)preferredStatusBarStyle{ 
    return UIStatusBarStyleLightContent; 
 } 

更新:
还要检查developers-guide-to-the-ios-7-status-bar

答案 3 :(得分:25)

在iOS 7中处理状态栏的背景颜色时,有两种情况

案例1:使用导航栏查看

在这种情况下,请在viewDidLoad方法中使用以下代码

 UIApplication *app = [UIApplication sharedApplication];
 CGFloat statusBarHeight = app.statusBarFrame.size.height;

 UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, -statusBarHeight, [UIScreen mainScreen].bounds.size.width, statusBarHeight)];
 statusBarView.backgroundColor = [UIColor yellowColor];
 [self.navigationController.navigationBar addSubview:statusBarView];

案例2:没有导航栏的视图

在这种情况下,请在viewDidLoad方法中使用以下代码

 UIApplication *app = [UIApplication sharedApplication];
 CGFloat statusBarHeight = app.statusBarFrame.size.height;

 UIView *statusBarView =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, statusBarHeight)];
 statusBarView.backgroundColor  =  [UIColor yellowColor];
 [self.view addSubview:statusBarView];

来源链接http://code-ios.blogspot.in/2014/08/how-to-change-background-color-of.html

答案 4 :(得分:14)

您可以在应用程序启动期间或视图控制器的viewDidLoad期间为状态栏设置背景颜色。

extension UIApplication {

    var statusBarView: UIView? {
        return value(forKey: "statusBar") as? UIView
    }

}

// Set upon application launch, if you've application based status bar
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
        return true
    }
}


or 
// Set it from your view controller if you've view controller based statusbar
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
    }

}



结果如下:

enter image description here


以下是关于状态栏更改的Apple Guidelines/Instruction。只有黑暗&状态栏中允许使用灯光(而黑色)。

以下是 - 如何更改状态栏样式:

如果要设置状态栏样式,应用程序级别,请在“.plist”文件中将UIViewControllerBasedStatusBarAppearance设置为NO

如果您要在视图控制器级别设置状态栏样式,请按照以下步骤操作:

  1. 如果您只需要在UIViewController级别设置状态栏样式,请在UIViewControllerBasedStatusBarAppearance文件中将YES设置为.plist
  2. 在viewDidLoad添加功能 - setNeedsStatusBarAppearanceUpdate

  3. 覆盖视图控制器中的preferredStatusBarStyle。

  4. -

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setNeedsStatusBarAppearanceUpdate()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    

答案 5 :(得分:14)

在iOS 7中,状态栏没有背景,因此如果您在其后面放置一个20px高的黑色视图,您将获得与iOS 6相同的结果。

另外,您可能需要阅读iOS 7 UI Transition Guide以获取有关该主题的更多信息。

答案 6 :(得分:8)

在ViewDidLoad方法中写下这个:

if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars=NO;
    self.automaticallyAdjustsScrollViewInsets=NO;
}

它在一定程度上修复了我和其他UI错位的状态栏颜色。

答案 7 :(得分:6)

对于背景,您可以轻松添加视图,例如:

 UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,320, 20)];
    view.backgroundColor=[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.1];
    [navbar addSubview:view];

其中“navbar”是UINavigationBar。

我希望它可以帮到你!

答案 8 :(得分:6)

只是为了添加Shahid的答案 - 你可以考虑方向变化或使用它的不同设备(iOS7 +):

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  ...

  //Create the background
  UIView* statusBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.window.frame.size.width, 20)];
  statusBg.backgroundColor = [UIColor colorWithWhite:1 alpha:.7];

  //Add the view behind the status bar
  [self.window.rootViewController.view addSubview:statusBg];

  //set the constraints to auto-resize
  statusBg.translatesAutoresizingMaskIntoConstraints = NO;
  [statusBg.superview addConstraint:[NSLayoutConstraint constraintWithItem:statusBg attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:statusBg.superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
  [statusBg.superview addConstraint:[NSLayoutConstraint constraintWithItem:statusBg attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:statusBg.superview attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
  [statusBg.superview addConstraint:[NSLayoutConstraint constraintWithItem:statusBg attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:statusBg.superview attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]];
  [statusBg.superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[statusBg(==20)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(statusBg)]];
  [statusBg.superview setNeedsUpdateConstraints];
  ...
}

答案 9 :(得分:5)

这是一个完整的复制和粘贴解决方案,带有

绝对正确的解释

涉及的每个问题。

感谢Warif Akhand Rishi

关于keyPath statusBarWindow.statusBar的惊人发现。好的。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // handle the iOS bar!

    // >>>>>NOTE<<<<<
    // >>>>>NOTE<<<<<
    // >>>>>NOTE<<<<<
    // "Status Bar Style" refers to the >>>>>color of the TEXT<<<<<< of the Apple status bar,
    // it does NOT refer to the background color of the bar. This causes a lot of confusion.
    // >>>>>NOTE<<<<<
    // >>>>>NOTE<<<<<
    // >>>>>NOTE<<<<<

    // our app is white, so we want the Apple bar to be white (with, obviously, black writing)

    // make the ultimate window of OUR app actually start only BELOW Apple's bar....
    // so, in storyboard, never think about the issue. design to the full height in storyboard.
    let h = UIApplication.shared.statusBarFrame.size.height
    let f = self.window?.frame
    self.window?.frame = CGRect(x: 0, y: h, width: f!.size.width, height: f!.size.height - h)

    // next, in your plist be sure to have this: you almost always want this anyway:
    // <key>UIViewControllerBasedStatusBarAppearance</key>
    // <false/>

    // next - very simply in the app Target, select "Status Bar Style" to Default.
    // Do nothing in the plist regarding "Status Bar Style" - in modern Xcode, setting
    // the "Status Bar Style" toggle simply sets the plist for you.

    // finally, method A:
    // set the bg of the Apple bar to white.  Technique courtesy Warif Akhand Rishi.
    // note: self.window?.clipsToBounds = true-or-false, makes no difference in method A.
    if let sb = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView {
        sb.backgroundColor = UIColor.white
        // if you prefer a light gray under there...
        //sb.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.9, alpha: 1)
    }

    /*
    // if you prefer or if necessary, method B:
    // explicitly actually add a background, in our app, to sit behind the apple bar....
    self.window?.clipsToBounds = false // MUST be false if you use this approach
    let whiteness = UIView()
    whiteness.frame = CGRect(x: 0, y: -h, width: f!.size.width, height: h)
    whiteness.backgroundColor = UIColor.green
    self.window!.addSubview(whiteness)
    */

    return true
}

答案 10 :(得分:4)

更改状态栏的背景颜色: 夫特:

let proxyViewForStatusBar : UIView = UIView(frame: CGRectMake(0, 0,self.view.frame.size.width, 20))    
        proxyViewForStatusBar.backgroundColor=UIColor.whiteColor()
        self.view.addSubview(proxyViewForStatusBar)

答案 11 :(得分:2)

快捷键4:-

//更改状态栏的背景颜色

    let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView

    statusBar?.backgroundColor = UIColor.red

答案 12 :(得分:1)

iTroid23解决方案适合我。我错过了Swift解决方案。所以这可能有用:

1)在我的plist中,我不得不添加:

<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>

2)我没有必要打电话给#34; setNeedsStatusBarAppearanceUpdate&#34;。

3)在swift中,我不得不将它添加到我的UIViewController中:

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent
}

答案 13 :(得分:1)

对于iOS 9上的swift 2.0

将以下内容放在app委托中,位于didFinishLaunchingWithOptions下:

    let view: UIView = UIView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 20))

    view.backgroundColor = UIColor.blackColor()  //The colour you want to set

    view.alpha = 0.1   //This and the line above is set like this just if you want 
                          the status bar a darker shade of 
                          the colour you already have behind it.

    self.window!.rootViewController!.view.addSubview(view)

答案 14 :(得分:1)

我成功地自定义了StatusBar颜色非常简单,在方法中添加AppDelegate.cs文件:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)

下一个代码:

UIView statusBar = UIApplication.SharedApplication.ValueForKey(new NSString("statusBar")) as UIView;

if (statusBar!=null && statusBar.RespondsToSelector(new Selector("setBackgroundColor:")))
{
   statusBar.BackgroundColor = Color.FromHex(RedColorHex).ToUIColor();
}

所以你得到这样的东西:

enter image description here

链接:https://jorgearamirez.wordpress.com/2016/07/18/lesson-x-effects-for-the-status-bar/

答案 15 :(得分:0)

如果您使用的是UINavigationController,则可以使用以下扩展程序:

extension UINavigationController {
    private struct AssociatedKeys {
        static var navigationBarBackgroundViewName = "NavigationBarBackground"
    }

    var navigationBarBackgroundView: UIView? {
        get {
            return objc_getAssociatedObject(self,
                                        &AssociatedKeys.navigationBarBackgroundViewName) as? UIView
        }
        set(newValue) {
             objc_setAssociatedObject(self,
                                 &AssociatedKeys.navigationBarBackgroundViewName,
                                 newValue,
                                 .OBJC_ASSOCIATION_RETAIN)
        }
    }

    func setNavigationBar(hidden isHidden: Bool, animated: Bool = false) {
       if animated {
           UIView.animate(withDuration: 0.3) {
               self.navigationBarBackgroundView?.isHidden = isHidden
           }
       } else {
           navigationBarBackgroundView?.isHidden = isHidden
       }
    }

    func setNavigationBarBackground(color: UIColor, includingStatusBar: Bool = true, animated: Bool = false) {
        navigationBarBackgroundView?.backgroundColor = UIColor.clear
        navigationBar.backgroundColor = UIColor.clear
        navigationBar.barTintColor = UIColor.clear

        let setupOperation = {
            if includingStatusBar {
                self.navigationBarBackgroundView?.isHidden = false
                if self.navigationBarBackgroundView == nil {
                    self.setupBackgroundView()
                }
                self.navigationBarBackgroundView?.backgroundColor = color
            } else {
                self.navigationBarBackgroundView?.isHidden = true
                self.navigationBar.backgroundColor = color
            }
        }

        if animated {
            UIView.animate(withDuration: 0.3) {
                setupOperation()
            }
        } else {
            setupOperation()
        }
    }

    private func setupBackgroundView() {
        var frame = navigationBar.frame
        frame.origin.y = 0
        frame.size.height = 64

        navigationBarBackgroundView = UIView(frame: frame)
        navigationBarBackgroundView?.translatesAutoresizingMaskIntoConstraints = true
        navigationBarBackgroundView?.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]

        navigationBarBackgroundView?.isUserInteractionEnabled = false

        view.insertSubview(navigationBarBackgroundView!, aboveSubview: navigationBar)
    }
}

它基本上使导航栏背景透明,并使用另一个UIView作为背景。您可以调用导航控制器的setNavigationBarBackground方法,将导航栏背景颜色与状态栏一起设置。

请注意,如果要隐藏导航栏,则必须在扩展程序中使用setNavigationBar(hidden: Bool, animated: Bool)方法,否则用作背景的视图仍然可见。

答案 16 :(得分:0)

对于条形颜色:您为条形图提供自定义背景图像。

对于文字颜色:使用 About Text Handling in iOS

中的信息

答案 17 :(得分:0)

请试试这个。 在appdelegate类“didFinishLaunchingWithOptions”函数

中使用此代码

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; [application setStatusBarHidden:NO]; UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"]; if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) { statusBar.backgroundColor = [UIColor blackColor]; }

答案 18 :(得分:0)

快捷键4

Info.plist中添加此属性

查看基于控制器的状态栏外观为否

然后在AppDelegate内的didFinishLaunchingWithOptions中添加以下代码行

UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarStyle = .lightContent

答案 19 :(得分:0)

在Swift 5和Xcode 10.2中

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {

//Set status bar background colour
let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
statusBar?.backgroundColor = UIColor.red
//Set navigation bar subView background colour
   for view in controller.navigationController?.navigationBar.subviews ?? [] {
      view.tintColor = UIColor.white
      view.backgroundColor = UIColor.red
   }
})

在这里,我修复了状态栏背景色和导航栏背景色。如果您不希望导航栏显示颜色,则将其注释。

答案 20 :(得分:0)

快捷代码

            let statusBarView = UIView(frame: CGRect(x: 0, y: 0, width: view.width, height: 20.0))
            statusBarView.backgroundColor = UIColor.red
            self.navigationController?.view.addSubview(statusBarView)

答案 21 :(得分:0)

下面的代码段应与目标C一起使用。

   if (@available(iOS 13.0, *)) {
      UIView *statusBar = [[UIView alloc]initWithFrame:[UIApplication sharedApplication].keyWindow.windowScene.statusBarManager.statusBarFrame] ;
      statusBar.backgroundColor = [UIColor whiteColor];
      [[UIApplication sharedApplication].keyWindow addSubview:statusBar];
  } else {
      // Fallback on earlier versions

       UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
          if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
              statusBar.backgroundColor = [UIColor whiteColor];//set whatever color you like
      }
  }

答案 22 :(得分:0)

对于iOS 13 *和Swift 4,您可以像下面那样使用。

1->将基于View控制器的状态栏外观设置为NO

extension UIApplication {
var statusBarView: UIView? {
    if #available(iOS 13.0, *) {
       let statusBar =  UIView()

        statusBar.frame = UIApplication.shared.statusBarFrame

        UIApplication.shared.keyWindow?.addSubview(statusBar)
      
        return statusBar
    } else {
        let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
        return statusBar
    }
}

使用 在didFinishLaunchingWithOptions

UIApplication.shared.statusBarView?.backgroundColor = UIColor.red

答案 23 :(得分:0)

使用此扩展程序

extension UINavigationController {

  func setStatusBar(backgroundColor: UIColor) {
    let statusBarFrame: CGRect
    if #available(iOS 13.0, *) {
        statusBarFrame = view.window?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero
    } else {
        statusBarFrame = UIApplication.shared.statusBarFrame
    }
    let statusBarView = UIView(frame: statusBarFrame)
    statusBarView.backgroundColor = backgroundColor
    view.addSubview(statusBarView)
  }
}