NSSlider动画

6 macos cocoa nsslider

如何在更改其浮动值时创建NSSlider动画.我在努力:

[[mySlider animator] setFloatValue:-5];
Run Code Online (Sandbox Code Playgroud)

但这不起作用..只需更改没有动画的值.所以也许有人知道怎么做?

提前致谢.

she*_*ein 6

好的 - 所以这并不像我希望的那么快和漂亮,但它确实有效.您无法在滑块旋钮上实际使用动画师和核心动画 - 因为Core Animation仅适用于图层,并且无法访问滑块图层中的旋钮值.

所以我们不得不采用手动设置滑块值的动画.由于我们在Mac上执行此操作 - 您可以使用NSAnimation(在iOS上不可用).

NSAnimation的作用很简单 - 它提供了一个时序/插值机制,允许你进行动画处理(而不是核心动画,它也连接到视图并处理它们的变化).

要使用NSAnimation - 您最常将子类化并覆盖setCurrentProgress: 并将逻辑放在那里.

这是我实现这个的方法 - 我创建了一个名为的新NSAnimation子类 NSAnimationForSlider

NSAnimationForSlider.h:

@interface NSAnimationForSlider : NSAnimation  
{  
    NSSlider *delegateSlider;  
    float animateToValue;    
    double max;   
    double min;  
    float initValue;  
}  
@property (nonatomic, retain) NSSlider *delegateSlider;  
@property (nonatomic, assign) float animateToValue;    
@end  
Run Code Online (Sandbox Code Playgroud)

NSAnimationForSlider.m:

#import "NSAnimationForSlider.h"

@implementation NSAnimationForSlider
@synthesize delegateSlider;
@synthesize animateToValue;

-(void)dealloc
{
    [delegateSlider release], delegateSlider = nil;
}

-(void)startAnimation
{
    //Setup initial values for every animation
    initValue = [delegateSlider floatValue];
    if (animateToValue >= initValue) {
        min = initValue;
        max = animateToValue;
    } else  {
        min = animateToValue;
        max = initValue;
    }

    [super startAnimation];
}


- (void)setCurrentProgress:(NSAnimationProgress)progress
{
    [super setCurrentProgress:progress];

    double newValue;
    if (animateToValue >= initValue) {
        newValue = min + (max - min) * progress;        
    } else  {
        newValue = max - (max - min) * progress;
    }

    [delegateSlider setDoubleValue:newValue];
}

@end
Run Code Online (Sandbox Code Playgroud)

要使用它 - 您只需创建一个新的NSAnimationForSlider,将它作为委托给您的滑块,在每个动画之前设置它为animateToValue然后启动动画.

例如:

slider = [[NSSlider alloc] initWithFrame:NSMakeRect(50, 150, 400, 25)];
[slider setMaxValue:200];
[slider setMinValue:50];
[slider setDoubleValue:50];

[[window contentView] addSubview:slider];

NSAnimationForSlider *sliderAnimation = [[NSAnimationForSlider alloc] initWithDuration:2.0 animationCurve:NSAnimationEaseIn];
[sliderAnimation setAnimationBlockingMode:NSAnimationNonblocking];
[sliderAnimation setDelegateSlider:slider];
[sliderAnimation setAnimateToValue:150];

[sliderAnimation startAnimation];
Run Code Online (Sandbox Code Playgroud)