自定义iOS的状态栏

有时候,需要在状态栏上显示一些自定义信息,比如新浪微博的官方iOS客户端:告知用户信息处于发送队列、发送成功或者发送失败。


如上图,通过在状态栏显示自定义信息,可以给用户友好又不影响软件使用的提示。

为此,我们显得定义一个自定义状态栏类,包含一个显示信息的Label:

[cpp]  view plain copy
  1. @interface CustomStatusBar : UIWindow  
  2. {  
  3.     UILabel *_messageLabel;  
  4. }  
  5.   
  6. - (void)showStatusMessage:(NSString *)message;  
  7. - (void)hide;  
  8.   
  9. @end  

接着,设置大小和系统状态栏一致,背景为黑色:

[cpp]  view plain copy
  1. self.frame = [UIApplication sharedApplication].statusBarFrame;  
  2. self.backgroundColor = [UIColor blackColor];  

到这里,为了让自定义的状态栏可以让用户看到,还需要设置它的windowLevel。

在iOS中,windowLevel属性决定了UIWindow的显示层次。默认的windowLevel为UIWindowLevelNormal,即0.0。

系统定义了三个层次如下,具体可参考官方文档

[cpp]  view plain copy
  1. const UIWindowLevel UIWindowLevelNormal;  
  2. const UIWindowLevel UIWindowLevelAlert;  
  3. const UIWindowLevel UIWindowLevelStatusBar;  
  4. typedef CGFloat UIWindowLevel;  

为了能够覆盖系统默认的状态栏,我们把自定义的状态栏的windowLevel调高点:

[cpp]  view plain copy
  1. self.windowLevel = UIWindowLevelStatusBar + 1.0f;  

最后,为显示信息和隐藏添加一点无伤大雅的动画:

[cpp]  view plain copy
  1. - (void)showStatusMessage:(NSString *)message  
  2. {  
  3.     self.hidden = NO;  
  4.     self.alpha = 1.0f;  
  5.     _messageLabel.text = @"";  
  6.       
  7.     CGSize totalSize = self.frame.size;  
  8.     self.frame = (CGRect){ self.frame.origin, 0, totalSize.height };  
  9.       
  10.     [UIView animateWithDuration:0.5f animations:^{  
  11.         self.frame = (CGRect){ self.frame.origin, totalSize };  
  12.     } completion:^(BOOL finished){  
  13.         _messageLabel.text = message;  
  14.     }];  
  15. }  
  16.   
  17. - (void)hide  
  18. {  
  19.     self.alpha = 1.0f;  
  20.       
  21.     [UIView animateWithDuration:0.5f animations:^{  
  22.         self.alpha = 0.0f;  
  23.     } completion:^(BOOL finished){  
  24.         _messageLabel.text = @"";  
  25.         self.hidden = YES;  
  26.     }];;  
  27. }  

完整源码: https://github.com/siqin/CustomStatusBar
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值