陈斌彬的技术博客

Stay foolish,stay hungry

控制iOS 中的状态栏

iOS 7提供了两种状态栏的样式,用于控制状态栏文字的颜色。

typedef NS_ENUM(NSInteger, UIStatusBarStyle)  
{  
    UIStatusBarStyleDefault                                     = 0, // Dark content, for use on light backgrounds  
    UIStatusBarStyleLightContent     NS_ENUM_AVAILABLE_IOS(7_0) = 1, // Light content, for use on dark backgrounds  

    UIStatusBarStyleBlackTranslucent NS_ENUM_DEPRECATED_IOS(2_0, 7_0, "Use UIStatusBarStyleLightContent") = 1,  
    UIStatusBarStyleBlackOpaque      NS_ENUM_DEPRECATED_IOS(2_0, 7_0, "Use UIStatusBarStyleLightContent") = 2,  
};  

img

如果状态栏背景为浅色,应选用黑色字样式(UIStatusBarStyleDefault,默认值);如果背景为深色,则选用白色字样式(UIStatusBarStyleLightContent)。

iOS 7的UIViewController类里添加了几个新的方法,用于控制状态栏。

// These methods control the attributes of the status bar when this view controller is shown. They can be overridden in view controller subclasses to return the desired status bar attributes.  
- (UIStatusBarStyle)preferredStatusBarStyle NS_AVAILABLE_IOS(7_0); // Defaults to UIStatusBarStyleDefault  
- (BOOL)prefersStatusBarHidden NS_AVAILABLE_IOS(7_0); // Defaults to NO  

// This should be called whenever the return values for the view controller's status bar attributes have changed. If it is called from within an animation block, the changes will be animated along with the rest of the animation block.  
- (void)setNeedsStatusBarAppearanceUpdate NS_AVAILABLE_IOS(7_0);  

preferredStatusBarStyle方法用于指定当前视图控制器的状态栏样式,prefersStatusBarHidden方法指定是否隐藏状态栏。当修改了状态栏的字体颜色、显示或隐藏时,调用setNeedsStatusBarAppearanceUpdate方法告知系统需要刷新状态栏。

当然,以上方法都是iOS 7 SDK中新添加的方法。如果App需要适配旧的系统(iOS 6及早期版本),则不能使用上面的方式,而应该调用UIApplication类提供的方法,这也是iOS 7之前通用的方式:

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];  
[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];  

同时将Info.plist文件中的View controller–based status bar appearance键值设置为NO。