一提到延迟首先想到的是Sleep
[NSThread sleepForTimeInterval:10];
这只是等待十秒之后在执行
这里说的是
dispatch_after是延迟提交,不是延迟运行
先看看官方文档的说明:
Enqueue a block
for
execution at the specified time.
Enqueue,就是入队,指的就是将一个Block在特定的延时以后,加入到指定的队列中,不是在特定的时间后立即运行!。
[UILabel showStats:@"存储成功" atView:self.view]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self.navigationController popViewControllerAnimated:YES]; });
这两句代码执行之后的效果如下
uilabel 调用方法的延展
UILabel+Extension.h
#import <UIKit/UIKit.h> @interface UILabel (Extension) + (UILabel *)labelWithFont:(UIFont *)font textColor:(UIColor *)textColor numberOfLines:(NSInteger)lines textAlignment:(NSTextAlignment)textAlignment; /** * 自己粗略做的一个指示器=。= * * @param stats 提示内容 * @param view 添加到view上 */ + (void)showStats:(NSString *)stats atView:(UIView *)view; /** * 快速设置富文本 * * @param string 需要设置的字符串 * @param range 需要设置的范围(范围文字颜色显示为下厨房橘红色) */ - (void)setAttributeTextWithString:(NSString *)string range:(NSRange)range; @end
UILabel+Extension.m
#import "UILabel+Extension.h" @implementation UILabel (Extension) + (UILabel *)labelWithFont:(UIFont *)font textColor:(UIColor *)textColor numberOfLines:(NSInteger)lines textAlignment:(NSTextAlignment)textAlignment { UILabel *label = [[UILabel alloc] init]; label.font = font; label.textColor = textColor; label.numberOfLines = lines; label.textAlignment = textAlignment; return label; } + (void)showStats:(NSString *)stats atView:(UIView *)view { UILabel *message = [[UILabel alloc] init]; message.layer.cornerRadius = 10; message.clipsToBounds = YES; message.backgroundColor = RGBA(0, 0, 0, 0.8); message.numberOfLines = 0; message.font = [UIFont systemFontOfSize:15]; message.textColor = XCFLabelColorWhite; message.textAlignment = NSTextAlignmentCenter; message.alpha = 0; message.text = stats; CGSize size = [stats boundingRectWithSize:CGSizeMake(MAXFLOAT, 50) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil].size; message.frame = CGRectMake(0, 0, size.width + 20, size.height + 10); message.center = view.center; [view addSubview:message]; [UIView animateWithDuration:1.5 animations:^{ message.alpha = 1; } completion:^(BOOL finished) { [UIView animateWithDuration:2 animations:^{ message.alpha = 0; } completion:^(BOOL finished) { [message removeFromSuperview]; }]; }]; } - (void)setAttributeTextWithString:(NSString *)string range:(NSRange)range { NSMutableAttributedString *attrsString = [[NSMutableAttributedString alloc] initWithString:string]; [attrsString addAttribute:NSForegroundColorAttributeName value:XCFThemeColor range:range]; self.attributedText = attrsString; } @end