I've tried everything I can think of, including all the suggestions I've found here on SO and on other mailing lists, but I cannot figure out how to programmatically collapse an NSSplitView pane with an animation while Auto Layout is on.
Here's what I have right now (written in Swift for fun), but it falls down in multiple ways:
#IBAction func toggleSourceList(sender: AnyObject?) {
let isOpen = !splitView.isSubviewCollapsed(sourceList.view.superview!)
let position = (isOpen ? 0 : self.lastWidth)
if isOpen {
self.lastWidth = sourceList.view.frame.size.width
}
NSAnimationContext.runAnimationGroup({ context in
context.allowsImplicitAnimation = true
context.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
context.duration = self.duration
self.splitView.setPosition(position, ofDividerAtIndex: 0)
}, completionHandler: { () -> Void in
})
}
The desired behavior and appearance is that of Mail.app, which animates really nicely.
I have a full example app available at https://github.com/mdiep/NSSplitViewTest.
Objective-C:
[[splitViewItem animator] setCollapse:YES]
Swift:
splitViewItem.animator().collapsed = true
From Apple’s help:
Whether or not the child ViewController corresponding to the
SplitViewItem is collapsed in the SplitViewController. The default is
NO. This can be set with the animator proxy to animate the collapse or
uncollapse. The exact animation used can be customized by setting it
in the -animations dictionary with a key of "collapsed". If this is
set to YES before it is added to the SplitViewController, it will be
initially collapsed and the SplitViewController will not cause the
view to be loaded until it is uncollapsed. This is KVC/KVO compliant
and will be updated if the value changes from user interaction.
I was eventually able to figure this out with some help. I've transformed my test project into a reusable NSSplitView subclass: https://github.com/mdiep/MDPSplitView
For some reason none of the methods of animating frames worked for my scrollview. I didn't try animating the constraints though.
I ended up creating a custom animation to animate the divider position. If anyone is interested, here is my solution:
Animation .h:
#interface MySplitViewAnimation : NSAnimation <NSAnimationDelegate>
#property (nonatomic, strong) NSSplitView* splitView;
#property (nonatomic) NSInteger dividerIndex;
#property (nonatomic) float startPosition;
#property (nonatomic) float endPosition;
#property (nonatomic, strong) void (^completionBlock)();
- (instancetype)initWithSplitView:(NSSplitView*)splitView
dividerAtIndex:(NSInteger)dividerIndex
from:(float)startPosition
to:(float)endPosition
completionBlock:(void (^)())completionBlock;
#end
Animation .m
#implementation MySplitViewAnimation
- (instancetype)initWithSplitView:(NSSplitView*)splitView
dividerAtIndex:(NSInteger)dividerIndex
from:(float)startPosition
to:(float)endPosition
completionBlock:(void (^)())completionBlock;
{
if (self = [super init]) {
self.splitView = splitView;
self.dividerIndex = dividerIndex;
self.startPosition = startPosition;
self.endPosition = endPosition;
self.completionBlock = completionBlock;
[self setDuration:0.333333];
[self setAnimationBlockingMode:NSAnimationNonblocking];
[self setAnimationCurve:NSAnimationEaseIn];
[self setFrameRate:30.0];
[self setDelegate:self];
}
return self;
}
- (void)setCurrentProgress:(NSAnimationProgress)progress
{
[super setCurrentProgress:progress];
float newPosition = self.startPosition + ((self.endPosition - self.startPosition) * progress);
[self.splitView setPosition:newPosition
ofDividerAtIndex:self.dividerIndex];
if (progress == 1.0) {
self.completionBlock();
}
}
#end
I'm using it like this - I have a 3 pane splitter view, and am moving the right pane in/out by a fixed amount (235).
- (IBAction)togglePropertiesPane:(id)sender
{
if (self.rightPane.isHidden) {
self.rightPane.hidden = NO;
[[[MySplitViewAnimation alloc] initWithSplitView:_splitView
dividerAtIndex:1
from:_splitView.frame.size.width
to:_splitView.frame.size.width - 235
completionBlock:^{
;
}] startAnimation];
}
else {
[[[MySplitViewAnimation alloc] initWithSplitView:_splitView
dividerAtIndex:1
from:_splitView.frame.size.width - 235
to:_splitView.frame.size.width
completionBlock:^{
self.rightPane.hidden = YES;
}] startAnimation];
}
}
/// Collapse the sidebar
func collapsePanel(_ number: Int = 0){
guard number < self.splitViewItems.count else {
return
}
let panel = self.splitViewItems[number]
if panel.isCollapsed {
panel.animator().isCollapsed = false
} else {
panel.animator().isCollapsed = true
}
}
I will also add, because it took me quite a while to figure this out, that setting collapseBehavior = .useConstraints on your NSSplitViewItem (or items) may help immensely if you have lots of constraints defining the layouts of your subviews. My split view animations didn't look right until I did this. YMMV.
If you're using Auto-Layout and you want to animate some aspect of the view's dimensions/position, you might have more luck animating the constraints themselves. I've had a quick go with an NSSplitView but have so far only met with limited success. I can get a split to expand and collapse following a button push, but I've ended up having to try to hack my way around loads of other problems caused by interfering with the constraints. In case your unfamiliar with it, here's a simple constraint animation:
- (IBAction)animate:(NSButton *)sender {
/* Shrink view to invisible */
NSLayoutConstraint *constraint = self.viewWidthConstraint;
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
[[NSAnimationContext currentContext] setDuration:0.33];
[[NSAnimationContext currentContext] setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
[[constraint animator] setConstant:0];
} completionHandler:^{
/* Do Some clean-up, if required */
}];
Bear in mind you can only animate a constraints constant, you can't animate its priority.
NSSplitViewItem (i.e. arranged subview of NSSplitView) can be fully collapsed, if it can reach Zero dimension (width or height). So, we just need to deactivate appropriate constrains before animation and allow view to reach Zero dimension. After animation we can activate needed constraints again.
See my comment for SO question How to expand and collapse NSSplitView subviews with animation?.
This is a solution that doesn't require any subclasses or categories, works without NSSplitViewController (which requires macOS 10.10+), supports auto layout, animates the views, and works on macOS 10.8+.
As others have suggested, the solution is to use an NSAnimationContext, but the trick is to set context.allowsImplicitAnimation = YES (Apple docs). Then just set the divider position as one would normally.
#import <Quartz/Quartz.h>
#import <QuartzCore/QuartzCore.h>
- (IBAction)toggleLeftPane:(id)sender
{
[NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull context) {
context.allowsImplicitAnimation = YES;
context.duration = 0.25; // seconds
context.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
if ([self.splitView isSubviewCollapsed:self.leftPane]) {
// -> expand
[self.splitView setPosition:self.leftPane.frame.size.width ofDividerAtIndex:0];
} else {
// <- collapse
_lastLeftPaneWidth = self.leftPane.frame.size.width;
// optional: remember current width to restore to same size
[self.splitView setPosition:0 ofDividerAtIndex:0];
}
[self.splitView layoutSubtreeIfNeeded];
}];
}
Use auto layout to constrain the subviews (width, min/max sizes, etc.). Make sure to check "Core Animation Layer" in Interface Builder (i.e. set views to be layer backed) for the split view and all subviews — this is required for the transitions to be animated. (It will still work, but without animation.)
A full working project is available here: https://github.com/demitri/SplitViewAutoLayout.
Related
I have an app which I'm updating to auto layout and size classes and I'm getting some weird behaviour with the label on a button.
The button should be a circle and have a label in the centre. I'm implementing my own subclass so I can reuse it.
Here's the storyboard:
and the code for the class which extends UIButton:
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self setBackgroundImage:[UIImage imageNamed:#"selected-green"] forState:UIControlStateHighlighted ];
self.layer.borderColor = [UIColor tlbWhiteColor].CGColor;
self.layer.borderWidth = 10;
}
return self;
}
-(void) layoutSubviews {
self.layer.cornerRadius = self.frame.size.width / 2;
}
With this the appears as expected but there is no label. On debugging I see that the frame of the label has 0 height and width. So I extended layoutSubviews:
-(void) layoutSubviews {
self.layer.cornerRadius = self.frame.size.width / 2;
if (self.titleLabel.frame.size.width == 0) {
[self.titleLabel sizeToFit];
[self setNeedsLayout];
[self layoutIfNeeded];
}
}
The label then appears, but it's in the wrong place:
The only extra info I can offer is that in Reveal the button has weird height and width constraints added:
The titleInsets are all at 0.
Help hugely appreciated.
I don't think you need the layoutSubviews override. I think it's a hack and it's hiding your real issue.
What are the constraints on the 'Go' label? How are you centering it in the UIButton? Also what is the height constraint on the label?
My suggestion would be to put both the UIButton and the Go label inside a container view and centre the label inside the container view. The container view should have the same height and width as the UIButton inside it.
Also are you changing the frames of the views programmatically somewhere in the app? Those weird constraints you talk about in reveal point to that.
As per your requirements:
- (void)viewDidLoad {
[super viewDidLoad];
view_1.layer.cornerRadius = 10; //view_1 is white color
view_1.layer.masksToBounds = YES;
view_2.layer.cornerRadius = _view_2.frame.size.width/2;//view_2 is green color
view_2.layer.masksToBounds = YES;
}
output
Ok, this was a real school boy error.
When the docs said 'The implementation of this method is empty before iOS 6' I for some reason took this to mean there's no need to call super on layoutSubviews.
So the fix was:
-(void) layoutSubviews {
[super layoutSubviews]; // <<<<< THIS WAS MISSING
self.layer.cornerRadius = self.frame.size.width / 2;
self.layer.masksToBounds = YES;
}
i created a image view
for(int i=0; i<pcount; i++)
{
int x = rand() % 350;
int y = rand() % 350;
NSRect rect = NSMakeRect((x+10),(y+10), 200, 200);
//NSImageView *imageView
imageView1 = [[NSImageView alloc]initWithFrame:rect];
[imageView1 setTag:i];
// imageView = [[NSImageView alloc]initWithFrame:rect];
// [imageView1 rotateByAngle:rand() % 150];
[imageView1 setImageScaling:NSScaleToFit];
[imageView1 canBecomeKeyView];
NSImage *theImage = [[NSImage alloc]initWithContentsOfURL:(NSURL*)[patharray objectAtIndex:(i)]];
[imageView1 setImage:theImage];
[[imageView1 cell] setHighlighted:YES];
[[layoutCustom view] addSubview:imageView1 positioned:NSWindowMovedEventType relativeTo:nil];}
now how can select each image view by mouse click ? thanks in advance.
I'm assuming here that you have your reasons for not using existing collection views. So from what I read in your code you have layoutCustom.view, which contains a bunch of NSImageViews. Here are two options:
In your layoutCustom object implement the mouseDown: (or mouseUp: or both). Take the event location convert it view coordinates and look for any subview for which CGRectContainsPoint(subview.frame, mouseDownPoint) return YES. You should select that view.
Subclass NSImageView and implement mouseDown: (or mouseUp: or both). On mouseDown: simply set a "selected" flag. Either the view can draw something itself when selected or the layoutCustom object can observe the property and draw the selection accordingly.
I would prefer option 1 because it simpler, requires fewer classes and fewer interactions between objects.
// Option 1 (in layoutCustom class)
- (void) mouseDown:(NSEvent*)theEvent {
CGPoint mouseDownPoint = [self convertPoint:theEvent.locationInWindow fromView:nil];
for (NSView *view in self.subviews) {
if (CGRectContainsPoint(view.frame, mouseDownPoint)) {
// Do something to remember the selection.
// Draw the selection in drawRect:
[self setNeedsDisplay:YES];
}
}
}
// Option 2 (in Custom subclass of NSImage)
- (void) mouseDown:(NSEvent*)theEvent {
self.selected = !self.selected;
}
// Option 2 (in layoutCustom class)
- (void) addSubview:(NSView*)view positioned:(NSWindowOrderingMode)place relativeTo:(NSView*)otherView {
[super addSubview:view positioned:place relativeTo:otherView];
[self startObservingSubview:view];
}
- (void) willRemoveSubview:(NSView*)view {
[self stopObservingSubview:view];
}
- (void) startObservingSubview:(NSView*)view {
// Register your KVO here
// You MUST implement observeValueForKeyPath:ofObject:change:context:
}
- (void) stopObservingSubview:(NSView*)view {
// Remove your KVO here
}
I've got a better idea: Instead of fighting with converting mouse clicks in a view to coordinates and then figuring out how to map it to the right subview or sub-image, why not have one big (or scrolling?) view and then add your images as giant "NSButton" objects (set to custom type), where the button images can be the images you want to add.
As for how to select each image? You can either subclass "NSButton" and keep track of some custom data within it, or you can use a "tag" to figure out which button was pressed in your "IBAction" method and then decide what to do with it.
Another approach might be to embed your images into NSTableView cells...
I am attempting to make a basic game which requires a serious of buttons to control player movement. Keep in mind I am using cocos-2d. My goal is to have the buttons be holdable and move a sprite when held down. The code i am using now looks like this.
CCMenuItemHoldable.h
#interface CCMenuItemSpriteHoldable : CCMenuItemSprite {
bool buttonHeld;
}
#property (readonly, nonatomic) bool buttonHeld;
CCMenuItemHoldable.m
#implementation CCMenuItemSpriteHoldable
#synthesize buttonHeld;
-(void) selected
{
[super selected];
buttonHeld = true;
[self setOpacity:128];
}
-(void) unselected
{
[super unselected];
buttonHeld = false;
[self setOpacity:64];
}
#end
and for the set up of the buttons
rightBtn = [CCMenuItemSpriteHoldable itemFromNormalSprite:[CCSprite spriteWithFile:#"art/hud/right.png"] selectedSprite:[CCSprite spriteWithFile:#"art/hud/right.png"] target:self selector:#selector(rightButtonPressed)];
CCMenu *directionalMenu = [CCMenu menuWithItems:leftBtn, rightBtn, nil];
[directionalMenu alignItemsHorizontallyWithPadding:0];
[directionalMenu setPosition:ccp(110,48)];
[self addChild:directionalMenu];
This all seems to work fine but when i do
-(void)rightButtonPressed:(id) sender
{
if([sender buttonHeld])
targetX = 10;
else{
targetX = 0;
}
}
The crash has been fixed but I am trying to get my sprite to move. In my game tick function I add the value of targetX to the position of the sprite on a timer, still no movement.
Please, always include a crash log when asking questions about crashes.
In your case, I can guess the problem. You are adding this selector:
#selector(rightButtonPressed)
Your method is called
rightButtonPressed:(id)sender
Which would be, as a selector, rightButtonPressed: - note the colon indicating that an argument is passed. Either change the method so it has no argument, or add a colon to the selector when you create the button.
The crash log would be telling you this - it would say "unrecognised selector sent to..." with the name of the receiving class, and the name of the selector.
I'm trying to get my NSTextField to have its height grow (much like in iChat or Adium) once the user types enough text to overflow the width of the control (as asked on this post)
I've implimented the accepted answer yet I can't seem to get it to work. I have uploaded my attempt at http://scottyob.com/pub/autoGrowingExample.zip
Ideally, when the text grows, the containing window should grow with it, but I'm trying baby steps here.
Solved it! (Inspired by https://github.com/jerrykrinock/CategoriesObjC/blob/master/NS(Attributed)String%2BGeometrics/NS(Attributed)String%2BGeometrics.m )
Reading the Apple Documentation is usually helpful. Apple has engineered all this text layout stuff to be powerful enough to handle all sorts of complicated edge cases which is sometimes extremely helpful, and sometimes not.
Firstly, I set the text field to wrap lines on word break, so we actually get multiple lines. (Your example code even had an if statement so it did nothing at all when wrapping was turned off).
The trick to this one was to note that when text is being edited, it’s printed by a ‘field editor’ – a heavy weight NSTextView object, owned by an NSWindow, that’s reused by whatever NSTextField is currently the ‘first responder’ (selected). The NSTextView has a single NSTextContainer (rectangle where text goes), which has a NSLayoutManager to layout the text. We can ask the layout manager how much space it wants to use up, to get the new height of our text field.
The other trick was to override the NSText delegate method - (void)textDidChange:(NSNotification *)notification to invalidate the intrinsic content size when the text is changed (so it doesn’t just wait to update when you commit changed by pressing return).
The reason I didn’t use cellSizeForBounds as you originally suggested was I couldn’t solve your problem – even when invalidating the intrinsic content size of the cell, cellSizeForBounds: continued to return the old size.
Find the example project on GitHub.
#interface TSTTextGrowth()
{
BOOL _hasLastIntrinsicSize;
BOOL _isEditing;
NSSize _lastIntrinsicSize;
}
#end
#implementation TSTTextGrowth
- (void)textDidBeginEditing:(NSNotification *)notification
{
[super textDidBeginEditing:notification];
_isEditing = YES;
}
- (void)textDidEndEditing:(NSNotification *)notification
{
[super textDidEndEditing:notification];
_isEditing = NO;
}
- (void)textDidChange:(NSNotification *)notification
{
[super textDidChange:notification];
[self invalidateIntrinsicContentSize];
}
-(NSSize)intrinsicContentSize
{
NSSize intrinsicSize = _lastIntrinsicSize;
// Only update the size if we’re editing the text, or if we’ve not set it yet
// If we try and update it while another text field is selected, it may shrink back down to only the size of one line (for some reason?)
if(_isEditing || !_hasLastIntrinsicSize)
{
intrinsicSize = [super intrinsicContentSize];
// If we’re being edited, get the shared NSTextView field editor, so we can get more info
NSText *fieldEditor = [self.window fieldEditor:NO forObject:self];
if([fieldEditor isKindOfClass:[NSTextView class]])
{
NSTextView *textView = (NSTextView *)fieldEditor;
NSRect usedRect = [textView.textContainer.layoutManager usedRectForTextContainer:textView.textContainer];
usedRect.size.height += 5.0; // magic number! (the field editor TextView is offset within the NSTextField. It’s easy to get the space above (it’s origin), but it’s difficult to get the default spacing for the bottom, as we may be changing the height
intrinsicSize.height = usedRect.size.height;
}
_lastIntrinsicSize = intrinsicSize;
_hasLastIntrinsicSize = YES;
}
return intrinsicSize;
}
#end
As a last note, I’ve never actually used auto layout myself – the demos look amazing, but whenever I actually try it myself, I can’t get it to work quite right and it makes things more complicated. However, in this case, I think it actually did save a bunch of work – without it, -intrinsicContentSize wouldn’t exist, and you’d possibly have to set the frame yourself, calculating the new origin as well as the new size (not too difficult, but just more code).
The solution by DouglasHeriot only works for fixed width text fields. In my app, I have text fields that I want to grow both horizontally and vertically. Therefore I modified the solution as follows:
AutosizingTextField.h
#interface AutosizingTextField : NSTextField {
BOOL isEditing;
}
#end
AutosizingTextField.m
#implementation AutosizingTextField
- (void)textDidBeginEditing:(NSNotification *)notification
{
[super textDidBeginEditing:notification];
isEditing = YES;
}
- (void)textDidEndEditing:(NSNotification *)notification
{
[super textDidEndEditing:notification];
isEditing = NO;
}
- (void)textDidChange:(NSNotification *)notification
{
[super textDidChange:notification];
[self invalidateIntrinsicContentSize];
}
-(NSSize)intrinsicContentSize
{
if(isEditing)
{
NSText *fieldEditor = [self.window fieldEditor:NO forObject:self];
if(fieldEditor)
{
NSTextFieldCell *cellCopy = [self.cell copy];
cellCopy.stringValue = fieldEditor.string;
return [cellCopy cellSize];
}
}
return [self.cell cellSize];
}
#end
There's a minor issue remaining: When typing spaces, the text jumps a bit to the left. However, that's not a problem in my app, because the text fields shouldn't contain spaces in most cases.
The solution of DouglasHeriot works great for me.
Here is the same code on Swift 4
class GrowingTextField: NSTextField {
var editing = false
var lastIntrinsicSize = NSSize.zero
var hasLastIntrinsicSize = false
override func textDidBeginEditing(_ notification: Notification) {
super.textDidBeginEditing(notification)
editing = true
}
override func textDidEndEditing(_ notification: Notification) {
super.textDidEndEditing(notification)
editing = false
}
override func textDidChange(_ notification: Notification) {
super.textDidChange(notification)
invalidateIntrinsicContentSize()
}
override var intrinsicContentSize: NSSize {
get {
var intrinsicSize = lastIntrinsicSize
if editing || !hasLastIntrinsicSize {
intrinsicSize = super.intrinsicContentSize
// If we’re being edited, get the shared NSTextView field editor, so we can get more info
if let textView = self.window?.fieldEditor(false, for: self) as? NSTextView, let textContainer = textView.textContainer, var usedRect = textView.textContainer?.layoutManager?.usedRect(for: textContainer) {
usedRect.size.height += 5.0 // magic number! (the field editor TextView is offset within the NSTextField. It’s easy to get the space above (it’s origin), but it’s difficult to get the default spacing for the bottom, as we may be changing the height
intrinsicSize.height = usedRect.size.height
}
lastIntrinsicSize = intrinsicSize
hasLastIntrinsicSize = true
}
return intrinsicSize
}
}
}
This solution also works when setting the string value of the text field and when it's resized by AutoLayout. It just uses the attributed text property to calculate the intrinsic content size whenever it's needed.
class AutoGrowingTextField: NSTextField {
var maximumHeight: CGFloat = 100
override var intrinsicContentSize: NSSize {
let height = attributedStringValue.boundingRect(
with: NSSize(width: bounds.width - 8, height: maximumHeight),
options: [NSString.DrawingOptions.usesLineFragmentOrigin]
).height + 5
return NSSize(width: NSView.noIntrinsicMetric, height: height)
}
override func textDidChange(_ notification: Notification) {
super.textDidChange(notification)
invalidateIntrinsicContentSize()
}
override func layout() {
super.layout()
invalidateIntrinsicContentSize()
}
}
And if you want to limit the size of the TextField (e.g.):
if (intrinsicSize.height > 100)
{
intrinsicSize = _lastIntrinsicSize;
}
else
{
_lastIntrinsicSize = intrinsicSize;
_hasLastIntrinsicSize = YES;
}
(Diff)
One thing I’m having trouble with is getting the NSTextField embedded in an NSScrollView and having it work properly (especially within an NSStackView). Going to look at whether it wouldn’t be easier with NSTextView instead.
I came up with an alternative solution that works well for me:
- (NSSize)intrinsicContentSize {
return [self sizeThatFits:NSMakeSize(self.frame.size.width, CGFLOAT_MAX)];
}
- (void)textDidChange:(NSNotification *)notification {
[super textDidChange:notification];
[self invalidateIntrinsicContentSize];
}
Basically we're just constraining the width to the given width of the element and based on that calculate the fitting height.
How can I create NSSlider animation when changing float value of it. I was trying:
[[mySlider animator] setFloatValue:-5];
but that didn't work.. just change the value without animation. So maybe someone knows how to do this?
Thanks in advance.
Ok - so this isn't as quick and pretty as I hoped but it works.
You can't actually use animators and Core Animation on the slider knob - because Core Animation works only on layers and there's no access to the knob values in the slider layer.
So we have to resort instead to manually animating slider value.
Since we're doing this on a Mac - you can use NSAnimation (which isn't available on iOS).
What NSAnimation does is simple - it provide an timing/interpolation mechanism to allow YOU to animate (as opposed to Core Animation which also connects to the views and handles the changes to them).
To use NSAnimation - you most commonly would subclass it and override setCurrentProgress:
and put your logic in there.
Here's how I implemented this - I created a new NSAnimation subclass called 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
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
To use it - you simply create a new NSAnimationForSlider, give it the slider you are working on as a delegate and before each animation you set it's animateToValue and then just start the animation.
For example:
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];
Your method works, but there's something much simpler.
You can use the animator proxy, you just need to tell it how to animate it.
To do this, you need to implement the defaultAnimationForKey: method from the NSAnimatablePropertyContainer protocol.
Here's a simple subclass of NSSlider that does this:
#import "NSAnimatableSlider.h"
#import <QuartzCore/QuartzCore.h>
#implementation NSAnimatableSlider
+ (id)defaultAnimationForKey:(NSString *)key
{
if ([key isEqualToString:#"doubleValue"]) {
return [CABasicAnimation animation];
} else {
return [super defaultAnimationForKey:key];
}
}
#end
Now you can simply use the animator proxy:
[self.slider.animator setDoubleValue:100.0];
Make sure to link the QuartzCore framework.
Here is a Swift version of IluTov answer, setting a floatValue with some animation config:
override class func defaultAnimation(forKey key: NSAnimatablePropertyKey) -> Any? {
if key == "floatValue" {
let animation = CABasicAnimation()
animation.timingFunction = .init(name: .easeInEaseOut)
animation.duration = 0.2
return animation
} else {
return super.defaultAnimation(forKey: key)
}
}