簡體   English   中英

如何在 iOS 7 上更改狀態欄背景顏色和文本顏色?

[英]How to change the status bar background color and text color on iOS 7?

我當前的應用程序在 iOS 5 和 6 上運行。

導航欄為橙色,狀態欄為黑色背景色和白色文本顏色。 但是,當我在 iOS 7 上運行相同的應用程序時,我觀察到狀態欄看起來透明,背景顏色與導航欄相同,並且狀態欄文本顏色為黑色。

因此,我無法區分狀態欄和導航欄。

如何使狀態欄看起來與 iOS 5 和 6 中的一樣,即黑色背景顏色和白色文本顏色? 如何以編程方式執行此操作?

警告:它不再適用於 iOS 13 和 Xcode 11。

================================================== ======================

我不得不嘗試尋找其他方法。 這不涉及窗口上的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
}

斯威夫特 3

func setStatusBarBackgroundColor(color: UIColor) {

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

    statusBar.backgroundColor = color
}

調用此表單application:didFinishLaunchingWithOptions對我application:didFinishLaunchingWithOptions

注意我們在應用商店中有一個具有這種邏輯的應用。 所以我想應用商店政策沒問題。


編輯:

使用風險自負。 形成評論者@Sebyddd

我有一個應用程序被拒絕的原因,而另一個被接受了。 他們確實認為這是私有 API 使用,因此您在審查過程中很幸運:) – Sebyddd

轉到您的應用程序info.plist

1) 將View controller-based status bar appearanceNO
2) 設置Status bar styleUIStatusBarStyleLightContent

然后轉到您的應用程序委托並將以下代碼粘貼到您設置 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];
}

希望它有幫助。

1) 在 plist 中將 UIViewControllerBasedStatusBarAppearance 設置為 YES

2)在viewDidLoad中做一個[self setNeedsStatusBarAppearanceUpdate];

3)添加如下方法:

 -(UIStatusBarStyle)preferredStatusBarStyle{ 
    return UIStatusBarStyleLightContent; 
 } 

更新:
還要檢查開發人員指南到 ios-7 狀態欄

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

您可以在應用程序啟動期間或視圖控制器的 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
    }

}



這是結果:

在此處輸入圖片說明


這是有關狀態欄更改的Apple 指南/說明 狀態欄中只允許深色和淺色(同時和黑色)。

這是 - 如何更改狀態欄樣式:

如果要設置狀態欄樣式、應用程序級別,請在“.plist”文件中將UIViewControllerBasedStatusBarAppearance設置為NO

如果您想設置狀態欄樣式,請在視圖控制器級別執行以下步驟:

  1. 如果您只需要在 UIViewController 級別設置狀態欄樣式,請在.plist文件中將UIViewControllerBasedStatusBarAppearance設置為YES
  2. 在viewDidLoad中添加函數setNeedsStatusBarAppearanceUpdate

  3. 覆蓋視圖控制器中的 preferredStatusBarStyle。

——

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

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

在 iOS 7 中狀態欄沒有背景,因此如果你在它后面放一個 20 像素高的黑色視圖,你將獲得與 iOS 6 相同的結果。

此外,您可能需要閱讀iOS 7 UI Transition Guide以獲取有關該主題的更多信息。

在你的 ViewDidLoad 方法中寫下這個:

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

它也在一定程度上修復了我的狀態欄顏色和其他 UI 錯位。

這是一個完整的復制和粘貼解決方案,帶有

絕對正確的解釋

涉及的每個問題。

感謝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
}

對於背景,您可以輕松添加視圖,例如:

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

其中“導航欄”是一個 UINavigationBar。

只是為了添加 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];
  ...
}

斯威夫特 4:

// 改變狀態欄背景顏色

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

statusBar?.backgroundColor = UIColor.red

更改狀態欄的背景顏色:Swift:

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

對於 iOS 9 上的 swift 2.0

將以下內容放在應用程序委托中的 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)

iTroid23 解決方案對我有用。 我錯過了 Swift 解決方案。 所以也許這有幫助:

1) 在我的 plist 中,我必須添加:

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

2)我不需要調用“setNeedsStatusBarAppearanceUpdate”。

3)在swift中,我必須將其添加到我的 UIViewController 中:

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

如果你使用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)方法,否則用作背景的視圖仍然可見。

試試這個。 在您的 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];
}

斯威夫特 4

Info.plist添加這個屬性

查看基於控制器的狀態欄外觀為 NO

然后在AppDelegatedidFinishLaunchingWithOptions添加這些代碼行

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

下面的代碼片段應該適用於 Objective 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
      }
  }

對於條形顏色:您為條形提供自定義背景圖像。

對於文本顏色:使用關於 iOS 中的文本處理中的信息

我成功地在AppDelegate.cs文件中添加了非常簡單的方法自定義 StatusBar 顏色:

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

所以你會得到這樣的東西:

在此處輸入圖片說明

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

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

在這里我修復了狀態欄背景顏色和導航欄背景顏色。 如果你不想導航欄顏色評論它。

斯威夫特代碼

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

您可以像下面這樣使用,適用於 iOS 13* 和 Swift 4。

1 -> 將基於視圖控制器的狀態欄外觀設置為 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

使用此擴展

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

Xcode 12 +

您可以使用“常規”選項卡中的 YourProject.xcodeproj 文件更改它,可以選擇更改狀態欄顏色,您可以使用此選項設置暗光或默認值,謝謝。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM