0

我正在尝试旋转 UIView。这个 UIView 代表时钟的秒指针。

我需要每秒更新一次。像这样:

- (void)startUpdates {
    _updateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(animatePointer) userInfo:nil repeats:YES];
}

当我需要它时停止它,如下所示:

- (void)stopUpdates {
    [_updateTimer invalidate];
    _updateTimer = nil;
}

并且每一秒都有动画,从一秒到下一秒,像这样:

- (void)animatePointer {

    NSDate *now = [NSDate date];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSSecondCalendarUnit fromDate:now];

    float angleForSeconds = (float)[components second] / 60.0;

    [UIView animateWithDuration:1.0 animations:^(void){
        _pointerGlow.layer.transform = CATransform3DMakeRotation((M_PI * 2) * angleForSeconds, 0, 0, 1);
    }];

}

这确实有效,但并不顺利。它每秒停顿几分之一秒,就像典型的挂钟一样。很好,但不是我想要的。

有什么办法可以让这个动画如丝般顺滑吗?

4

1 回答 1

1

您可以尝试使用与 60/秒的显示刷新率相关的 CADisplayLink。代码如下所示(请注意,我没有添加任何逻辑来停止显示链接,但我输入了您想要调用的方法):

#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface ViewController ()
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic) CFTimeInterval firstTimestamp;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self startDisplayLink];
}


- (void)startDisplayLink {
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
    [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)stopDisplayLink {
    [self.displayLink invalidate];
    self.displayLink = nil;
}

- (void)handleDisplayLink:(CADisplayLink *)displayLink {
    if (!self.firstTimestamp) self.firstTimestamp = displayLink.timestamp;
    NSTimeInterval elapsed = (displayLink.timestamp - self.firstTimestamp);
    self.arrow.layer.transform = CATransform3DMakeRotation((M_PI * 2) * elapsed/60, 0, 0, 1);
}
于 2013-08-04T01:56:14.030 回答