web-dev-qa-db-fra.com

Comment changer la couleur d'arrière-plan et la couleur du texte de la barre d'état sur iOS 7?

Mon application actuelle fonctionne sur iOS 5 et 6. 

La barre de navigation a une couleur orange et la barre d'état a une couleur d'arrière-plan noire avec une couleur de texte blanche. Cependant, lorsque j'exécute la même application sur iOS 7, j'observe que la barre d'état est transparente avec la même couleur d'arrière-plan orange que la barre de navigation et que la couleur du texte de la barre d'état est noire. 

Pour cette raison, je ne suis pas en mesure de faire la différence entre la barre d'état et la barre de navigation. 

Comment puis-je donner à la barre d'état la même apparence que dans iOS 5 et 6, c'est-à-dire avec une couleur d'arrière-plan noire et une couleur de texte blanche? Comment puis-je le faire par programme?

76
Rejeesh Rajan

Je devais essayer de chercher d'autres moyens. Ce qui n'implique pas addSubview sur la fenêtre. Parce que je me déplace vers le haut de la fenêtre lorsque le clavier est présenté.

Objectif c

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

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

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

Rapide

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
}

L'appel de ce formulaire application:didFinishLaunchingWithOptions a fonctionné pour moi.

N.B. Nous avons une application dans l'App Store avec cette logique. Donc, je suppose que ça va avec la politique de la boutique d'applications. 


Modifier:

À utiliser à vos risques et périls. Former le commentateur @Sebyddd

J'ai eu une application rejetée cause de cela, tandis qu'une autre a été acceptée juste. bien. Ils considèrent qu'il s'agit d'une API privée, vous êtes donc soumis à bonne chance pendant le processus de révision :) - Sebyddd

168
Warif Akhand Rishi

Allez à votre application info.plist 

1) Définissez View controller-based status bar appearance sur NO
2) Définissez Status bar style sur UIStatusBarStyleLightContent 

Ensuite, allez dans le délégué de votre application et collez le code suivant dans lequel vous définissez le contrôle RootViewController de Windows.

#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];
}

J'espère que ça aide.

106
Shahid Iqbal

1) Définissez UIViewControllerBasedStatusBarAppearance sur YES dans le plist.

2) dans viewDidLoad faire un [self setNeedsStatusBarAppearanceUpdate];

3) ajoutez la méthode suivante:

 -(UIStatusBarStyle)preferredStatusBarStyle{ 
    return UIStatusBarStyleLightContent; 
 } 

METTRE À JOUR:
Vérifiez également guide-de-développement-pour-la-barre-7-status-ios-7

27
Muruganandham K

Lors du traitement de la couleur d’arrière-plan de la barre d’état dans iOS 7, il existe deux cas.

Cas 1: Vue avec barre de navigation

Dans ce cas, utilisez le code suivant dans votre méthode 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];

Cas 2: Voir sans barre de navigation

Dans ce cas, utilisez le code suivant dans votre méthode 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];

Lien source http://code-ios.blogspot.in/2014/08/how-to-change-background-color-of.html

25
Teja Kumar Bethina

Dans iOS 7, la barre d'état n'a pas d'arrière-plan. Par conséquent, si vous placez une vue noire de 20 pixels de haut, vous obtiendrez le même résultat que iOS 6.

Vous pouvez également consulter le Guide de la transition de l'interface utilisateur iOS 7 pour plus d'informations sur le sujet.

14
Gabriele Petronella

Vous pouvez définir la couleur d'arrière-plan de la barre d'état lors du lancement de l'application ou de viewDidLoad de votre contrôleur de vue.

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
    }

}



Voici le résultat:

enter image description here


Voici Directives/Instructions Apple à propos du changement de barre d’état. Seuls les effets Dark & ​​Light (while & black) sont autorisés dans la barre d'état.

Voici - Comment changer le style de la barre d'état:

Si vous souhaitez définir le style de la barre d'état, le niveau de l'application, définissez UIViewControllerBasedStatusBarAppearance sur NO dans votre fichier `.plist '.

si vous souhaitez définir le style de la barre d'état, au niveau du contrôleur de vue, procédez comme suit:

  1. Définissez UIViewControllerBasedStatusBarAppearance sur YES dans le fichier .plist, si vous devez définir le style de la barre d'état au niveau UIViewController uniquement. 
  2. Dans la fonction d'ajout viewDidLoad - setNeedsStatusBarAppearanceUpdate

  3. écrasez preferredStatusBarStyle dans votre contrôleur de vue.

-

override func viewDidLoad() {
    super.viewDidLoad()
    self.setNeedsStatusBarAppearanceUpdate()
}

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}
14
Krunal

Ecrivez ceci dans votre méthode ViewDidLoad:

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

Il a également corrigé la couleur de la barre d'état pour moi et les autres erreurs de placement de l'interface utilisateur.

8
sanjana

Pour ajouter à la réponse de Shahid, vous pouvez prendre en compte les changements d’orientation ou différents appareils en utilisant ceci (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];
  ...
}
6
bendytree

pour l'arrière-plan, vous pouvez facilement ajouter une vue, comme dans l'exemple:

 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];

où "navbar" est un UINavigationBar.

j'espère que cela peut vous aider!

5
user3107409

Voici une solution totale, copier et coller, avec un

explication absolument correcte

de chaque problème impliqué.

Merci à Warif Akhand Rishi !

pour la découverte étonnante concernant keyPath statusBarWindow.statusBar. Bon un.

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
}
5
Fattie

Changer la couleur de fond de la barre d'état: Swift:

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

la solution iTroid23 a fonctionné pour moi. J'ai raté la solution Swift. Alors peut-être que cela est utile:

1) Dans mon plist je devais ajouter ceci:

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

2) Je n'ai pas eu besoin d'appeler "setNeedsStatusBarAppearanceUpdate".

3) Dans Swift, j'ai dû ajouter ceci à mon UIViewController:

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

Dans le cas de Swift 2.0 sur iOS 9 

Placez le texte suivant dans le délégué de l'application, sous 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)
1
Keegan Cruickshank

Code rapide

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

Dans Swift 5 et 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
   }
})

Ici, j'ai corrigé la couleur d'arrière-plan de la barre d'état et la couleur d'arrière-plan de la barre de navigation. Si vous ne voulez pas que la couleur de la barre de navigation le commente.

0
iOS

Swift 4

Dans Info.plist ajouter cette propriété

Affichez l'apparence de la barre d'état basée sur le contrôleur sur NO

et après cela dans AppDelegate à l'intérieur de didFinishLaunchingWithOptions, ajoutez ces lignes de code

UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarStyle = .lightContent
0
S.m.g. baquer

Pour la couleur de la barre: vous fournissez une image d’arrière-plan personnalisée pour la barre.

Pour la couleur du texte: utilisez les informations contenues dans À propos de la gestion de texte sous iOS

0
Chris Alan

Swift 4: -

// Changer la couleur de fond de la barre d'état

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

    statusBar?.backgroundColor = UIColor.red
0
V.Kumar

Veuillez essayer ceci . Utilisez ce code dans la fonction "didFinishLaunchingWithOptions" de votre classe appdelegate

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

0
Karthickkck

Si vous utilisez une UINavigationController, vous pouvez utiliser une extension comme celle-ci:

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)
    }
}

Fondamentalement, il rend le fond de la barre de navigation transparent et utilise un autre UIView comme arrière-plan. Vous pouvez appeler la méthode setNavigationBarBackground de votre contrôleur de navigation pour définir la couleur d'arrière-plan de la barre de navigation en même temps que la barre d'état. 

N'oubliez pas que vous devez ensuite utiliser la méthode setNavigationBar(hidden: Bool, animated: Bool) dans l'extension pour masquer la barre de navigation, sinon la vue utilisée comme arrière-plan sera toujours visible. 

0
halil_g