我想根据用户点击屏幕的速度创建一个在屏幕上上下移动的动画。我遇到的问题是我不知道如何创建无限循环,所以我正在触发一个会出现问题的计时器。这是我当前的代码。
-(void)setPosOfCider {
CGFloat originalY = CGRectGetMinY(cider.frame);
float oY = originalY;
float posY = averageTapsPerSecond * 100;
float dur = 0;
dur = (oY - posY) / 100;
[UIImageView animateWithDuration:dur animations:^(void) {
cider.frame = CGRectMake(768, 1024 - posY, 768, 1024);
}];
}
建议修复(不起作用):
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
scroll.pagingEnabled = YES;
scroll.scrollEnabled = YES;
scroll.contentSize = CGSizeMake(768 * 3, 1024); // 3 pages wide.
scroll.delegate = self;
self.speedInPointsPerSecond = 200000;
self.tapEvents = [NSMutableArray array];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self startDisplayLink];
}
-(IBAction)tapped {
[self.tapEvents addObject:[NSDate date]];
// if less than two taps, no average speed
if ([self.tapEvents count] < 1)
return;
// only average the last three taps
if ([self.tapEvents count] > 2)
[self.tapEvents removeObjectAtIndex:0];
// now calculate the average taps per second of the last three taps
NSDate *start = self.tapEvents[0];
NSDate *end = [self.tapEvents lastObject];
self.averageTapsPerSecond = [self.tapEvents count] / [end timeIntervalSinceDate:start];
}
- (void)startDisplayLink
{
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
self.lastTime = CACurrentMediaTime();
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (CGFloat)yAxisValueBasedUponTapsPerSecond
{
CGFloat y = 1024 - (self.averageTapsPerSecond * 100.0);
return y;
}
- (void)handleDisplayLink:(CADisplayLink *)displayLink
{
CFTimeInterval now = CACurrentMediaTime();
CGFloat elapsed = now - self.lastTime;
self.lastTime = now;
if (elapsed <= 0) return;
CGPoint center = self.cider.center;
CGFloat destinationY = [self yAxisValueBasedUponTapsPerSecond];
if (center.y == destinationY)
{
// we don't need to move it at all
return;
}
else if (center.y > destinationY)
{
// we need to move it up
center.y -= self.speedInPointsPerSecond * elapsed;
if (center.y < destinationY)
center.y = destinationY;
}
else
{
// we need to move it down
center.y += self.speedInPointsPerSecond * elapsed;
if (center.y > destinationY)
center.y = destinationY;
}
self.cider.center = center;
}