自訂狀態列的做法是:先隱藏系統的 statusbar,然後重新顯示一個 window 即可。直接上程式碼,可以拿去就用:
// // CustomStatusBar.h // CustomStatusBar // // Created by yb on 14/10/24. // Copyright (c) 2014年 yb. All rights reserved. // #import <UIKit/UIKit.h> @interface CustomStatusBar : UIWindow - (void)showStatusMessage:(NSString *)message; - (void)hideStatusBarWhenSendFinished; -(void)hideStatusBarWhenSendFailed; @end
//
// CustomStatusBar.m
// CustomStatusBar
//
// Created by yb on 14/10/24.
// Copyright (c) 2014年 yb. All rights reserved.
//
#import "CustomStatusBar.h"
@interface CustomStatusBar ()
@property(strong,nonatomic)UILabel *messageLabel;
@end
@implementation CustomStatusBar
- (instancetype)init
{
self = [super init];
if (self) {
self.frame=[UIApplication sharedApplication].statusBarFrame;
self.backgroundColor=[UIColor blackColor];
self.windowLevel=UIWindowLevelStatusBar+1.0f;
self.messageLabel=[[UILabel alloc]initWithFrame:self.bounds];
self.messageLabel.textColor=[UIColor whiteColor];
self.messageLabel.textAlignment=NSTextAlignmentCenter;
[self addSubview:_messageLabel];
}
return self;
}
- (void)showStatusMessage:(NSString *)message
{
self.hidden = NO;
self.alpha = 1.0f;
self.frame=[UIApplication sharedApplication].statusBarFrame;
self.messageLabel.frame=self.bounds;
CGSize totalSize = self.frame.size;
self.frame = (CGRect){ self.frame.origin, 0, totalSize.height };
[UIView animateWithDuration:0.5f animations:^{
self.frame = (CGRect){ self.frame.origin, totalSize };
self.messageLabel.text = message;
} completion:^(BOOL finished) {
}];
}
- (void)hideStatusBarWhenSendFinished
{
self.alpha = 1.0f;
[UIView animateWithDuration:2.0f animations:^
{
self.alpha = 0.0f;
CGRect frame=self.frame;
frame.size.height=0;
self.frame=frame;
self.messageLabel.text=@"發送成功!";
} completion:^(BOOL finished){
self.frame=CGRectZero;
self.hidden = YES;
}];
}
-(void)hideStatusBarWhenSendFailed
{
self.alpha = 1.0f;
[UIView animateWithDuration:2.0f animations:^
{
self.alpha = 0.0f;
CGRect frame=self.frame;
frame.size.height=0;
self.frame=frame;
self.messageLabel.text=@"發送失敗!";
} completion:^(BOOL finished){
self.frame=CGRectZero;
self.hidden = YES;
}];
}
@end
幾個設計上的關鍵點:windowLevel 設為 UIWindowLevelStatusBar+1.0f,確保這個提示條蓋在系統狀態列之上;showStatusMessage: 先把高度壓成 0 再動畫展開,做出「從上往下滑出」的效果;hide 系列方法則反過來收合並淡出。使用時建立實例後呼叫 showStatusMessage:,再依結果呼叫 hideStatusBarWhenSendFinished 或 hideStatusBarWhenSendFailed 即可。