ios---頂部提示框
一、簡介
有時候我們在做程式的時候,專案要求我們給使用者提示資訊的時候,從頂部自動下拉下來,前些日子我接到過這樣的需求,感覺用第三方的整合進來,如果以後修改樣式的話或者其它的需求會很麻煩,所以我自己寫了一個,程式碼有點簡單,請大家指導一下,有什麼意見或者有什麼疑問可以直接評論詢問我,很樂意和大家一起探討學習.
二、程式碼
1.建立一個單例,我是繼承NSOject的
+(instancetype)shareInstance
{
static ShowChatStateView *stateView = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
stateView = [[ShowChatStateView alloc]init];
});
return stateView;
}
2.初始化UIWindow
-(instancetype)init
{
self = [super init];
id <UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate];
if ([delegate respondsToSelector:@selector(window)])
{
self.window = [delegate performSelector:@selector(window)];
}
else
{
self.window = [[UIApplication sharedApplication] keyWindow];
}
[self createUI];
return self;
}
3.建立UILabel,使label唯一
-(void)createUI
{
if (self.label == nil)
{
self.label = [[UILabel alloc]initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, 64)];
self.label.textAlignment = NSTextAlignmentCenter;
self.label.textColor = [UIColor whiteColor];
self.label.backgroundColor = [MyTool colorWithString:@"50D2C2"];
self.label.font = [UIFont systemFontOfSize:Font(14.0f)];
self.label.alpha = 0.f;
}
if (self.label.superview == nil)
{
[self.window addSubview:self.label];
}
}
4.將文字顯示在Label上,並且從上面自動下拉,隔段時間(自己設定)在彈回去
-(void)show
{
if (!self.label.alpha)
{
self.label.alpha = 1.f;
CGRect rect = self.label.frame;
rect.origin.y = 0;
[UIView animateWithDuration:0.5 animations:^{
self.label.frame = rect;
} completion:^(BOOL finished) {
CGRect rect = self.label.frame;
rect.origin.y = -64;
[UIView animateWithDuration:0.5 delay:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
self.label.frame = rect;
} completion:^(BOOL finished) {
self.label.alpha = 0.f;
}];
}];
}
}
-(void)showLabelWithString:(NSString *)string
{
self.label.text = string;
[self show];
}
5.呼叫方法
[[ShowChatStateView shareInstance] showLabelWithString:@"您已簽過到"];
三、總結
我是利用UIWindow來實現下拉,這樣有導航欄也不影響view的向下彈出,如果你有更好的方法,歡迎討論,下面是效果圖: