ユーザーが画面をタップする速さに応じて、画面を上下に移動するアニメーションを作成したいと考えています。私が抱えている問題は、無限ループを作成する方法がわからないため、問題を引き起こすタイマーを起動していることです。これが私の現在のコードです。
-(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;
}