gpt4 book ai didi

ios - 如何围绕其中心旋转 UIView,持续时间为 1 分钟,间隔为 1 秒,动画如丝般流畅?

转载 作者:行者123 更新时间:2023-11-29 03:43:28 25 4
gpt4 key购买 nike

我正在尝试旋转 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);
}];

}

这确实有效,但并不顺利。它每秒都会停止一小会儿,就像典型的挂钟一样。不错,但不是我想要的。

有什么办法可以让这个动画变得丝般流畅吗?

最佳答案

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

#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);
}

关于ios - 如何围绕其中心旋转 UIView,持续时间为 1 分钟,间隔为 1 秒,动画如丝般流畅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18038253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com