一、簡介
有時候我們在做程序的時候,項目要求我們給用戶提示信息的時候,從頂部自動下拉下來,前些日子我接到過這樣的需求,感覺用第三方的集成進來,如果以后修改樣式的話或者其它的需求會很麻煩,所以我自己寫了一個,代碼有點簡單,請大家指導一下,有什么意見或者有什么疑問可以直接評論詢問我,很樂意和大家一起探討學習.
二、代碼
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的向下彈出,如果你有更好的方法,歡迎討論,下面是效果圖:

新聞熱點
疑難解答