最近看开源代码老是看到CADisplayLink,这个通常用在需要不停绘制页面的情况下,既然是QuatzCore框架中的,那绘制什么的效率肯定应该比用Timer高了吧....
用法和NSTimer很像。
CADisplayLink *dl = [CADisplayLink displayLinkWithTarget:self selector:@selector(timeCallback:)]; [dl addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; self.displayLink = dl; UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(20, 80, 200, 50)]; lab.backgroundColor = [UIColor blueColor]; [self.view addSubview:lab]; lab.textColor = [UIColor redColor]; lab.font = [UIFont systemFontOfSize:28]; lab.text = [NSString stringWithFormat:@"倒计时%ds", i]; _textLabel = lab;
下面是回调
- (void)timeCallback:(id)sender { int second = i--; NSString *str = [NSString stringWithFormat:@"倒计时%ds", second]; [self.textLabel setText:str]; CFTimeInterval time = self.displayLink.duration; NSLog(@"%f", time); // 0.01666666... NSLog(@"%ld", self.displayLink.frameInterval); int y = round(1.0/time); self.displayLink.frameInterval = y; // 约等于60帧,其实就是60啦 NSLog(@"%ld", self.displayLink.frameInterval); }
当然不用的时候记得
- (void)removeFromRunLoop:(NSRunLoop *)runloop forMode:(NSString *)mode; 或者 - (void)invalidate;
@property(readonly, nonatomic) CFTimeInterval timestamp; // 当前时间 @property(readonly, nonatomic) CFTimeInterval duration; // 每帧的间隔
测试结果是1/60 s调用一次callback。
时间: 2024-10-12 04:49:22