// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
@end
// VCView.h
#import <UIKit/UIKit.h>
@interface VCView : UIView
@end
// VCView.m
#import "VCView.h"
@implementation VCView
- (void)awakeFromNib {
// 添加定时器
// [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(update) userInfo:nil repeats:YES];
// 什么时候调用指定的方法?
// 当下一次屏幕刷新时调用(屏幕每一秒刷新60)
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
// 想要让CADisplayLink工作, 必须得要添加到主运行循环当中.
[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
// setNeedsDisplay底层会调用drawRect,并不是立马调用的.只是设了一个调用的标志.
// 等下一次屏幕刷新时才去调用drawRect
}
static int _snowY = 0;
- (void)update {
NSLog(@"%s",__func__);
_snowY += 10;
if (_snowY > self.bounds.size.height) {
_snowY = 0;
}
// 重绘
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
//加载图片
UIImage *image = [UIImage imageNamed:@"雪花"];
[image drawAtPoint:CGPointMake(0, _snowY)];
}
@end