NSSlider animation - macos

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

Related

UICollisionBehavior with iOS9 seems to stop 1.5 points away from boundary: My bug or Apple's?

In my app, I use UIKit Dynamics including a UICollisionBehavior to have a menu bounce when it opens and when it closes. The code I'm using for this is below. This has been working fine for iOS8. With iOS9 (including iOS9.1 beta 2 just released), however, I'm finding an odd issue. On the surface, the menu I'm bouncing with this bouncing animation wasn't full closing after opening and then closing it. Looking more closely, I find that the boundaries for the UICollisionBehavior are computed with the same values across iOS8 and iOS9.
Menu opening collision boundary: (798,330) to (1024,330)
Which represents a line, on screen, where the bottom of the menu should finally rest after opening and bouncing.
Menu closing collision boundary: (798,-280) to (1024,-280)
Which represents a line, off screen, where the top of the menu should finally rest after closing and bouncing.
The problem comes in iOS9 where the menu UIView doesn't actually end up resting finally at these boundaries. After opening, the menu frame looks like this with iOS9:
(798, -1.5; 226, 330) [This is: (x, y; w, h)]
and after closing, the menu frame looks like:
(798, -278.5; 226, 330)
BUT, this should actually be:
(798, 0; 226, 330) (after opening)
(798, -280; 226, 330) (after closing)
Anyone else seeing these issues with iOS9 and collision behaviors?
I'm about to put a hack in my code (search for "HACK" below), which I'll make selective for iOS9, but I really don't like these hacks!
BounceAnimation.h
//
// BounceAnimation.h
// Petunia
//
// Created by Christopher Prince on 12/18/14.
// Copyright (c) 2014 Spastic Muffin, LLC. All rights reserved.
//
// Animates an object through a straight line path, up, down, left or right until it lands, after which it bounces. This requires iOS8 or later.
#import <Foundation/Foundation.h>
#interface BounceAnimation : NSObject
// distnace is for the viewToAnimate to travel until it lands and bounces, in points. You must set this before calling run.
- (instancetype) initWithReferenceView: (UIView *) referenceView viewToAnimate: (UIView *) viewToAnimate andDistance: (CGFloat) distance;
// Direction and distance will be obtained from animateToPoint, and should be consistent with the constraints for the direction property below. I.e., the animateToPoint should be down, left, right, or up from the origin of the viewToAnimate.
- (instancetype) initWithReferenceView: (UIView *) referenceView viewToAnimate: (UIView *) viewToAnimate andFinalPoint: (CGPoint) animateToPoint;
// One shot animation. You can only call run once.
- (void) run;
// Called when animation completes, if given. Called when all the bouncing is done.
#property (nonatomic, strong) void (^completion)(void);
// Called when first contact is made with the boundary, just as the first bounce is about to begin.
#property (nonatomic, strong) void (^firstImpactCallback)(void);
// Only keeps weak references to the views passed in the init method.
#property (nonatomic, weak, readonly) UIView *referenceView;
#property (nonatomic, weak, readonly) UIView *viewToAnimate;
// Rate at which the object accelerates towards the boundary. Same units as magnitude for UIGravityBehavior. Defaults to 1.0.
#property (nonatomic) CGFloat accelerationRate;
// Defaults to 0. Units are points per second.
#property (nonatomic) CGFloat initialVelocity;
// This is a unit vector.
// dx (first component) is rightwards; e.g., dx=0, no right/left; dx=-1, is left one unit
// dy (second component) is downwards; e.g., dy=1, down one unit.
// Defaults to (0, 1), downwards.
// Right now, dx and dy can be 0, 1, or -1. One of dx and dy must be 0.
#property (nonatomic, readonly) CGVector direction;
#end
BounceAnimation.m
//
// BounceAnimation.m
// Petunia
//
// Created by Christopher Prince on 12/18/14.
// Copyright (c) 2014 Spastic Muffin, LLC. All rights reserved.
//
#import "BounceAnimation.h"
#import "Vector.h"
#import "UIDevice+Extras.h"
#interface BounceAnimation()<UIDynamicAnimatorDelegate, UICollisionBehaviorDelegate>
{
UIDynamicAnimator *_animator;
UIGravityBehavior *_gravityBehavior;
UICollisionBehavior *_collision;
UIDynamicItemBehavior *_velocity;
CGPoint _linearVelocity;
CGFloat _distanceInPoints;
BOOL _calledFirstImpactCallback;
}
#property (nonatomic, weak) UIView *referenceView;
#property (nonatomic, weak) UIView *viewToAnimate;
#property (nonatomic) CGVector direction;
#end
#define INITIAL_GRAVITY_MAGNITUDE 1.0
#implementation BounceAnimation
- (void) setupWithReferenceView: (UIView *) referenceView andViewToAnimate: (UIView *) viewToAnimate;
{
AssertIf([UIDevice ios7OrEarlier], #"Don't have at least iOS8!");
self.referenceView = referenceView;
self.viewToAnimate = viewToAnimate;
_animator = [[UIDynamicAnimator alloc] initWithReferenceView:referenceView];
_animator.delegate = self;
_gravityBehavior = [[UIGravityBehavior alloc] initWithItems:#[viewToAnimate]];
_gravityBehavior.magnitude = INITIAL_GRAVITY_MAGNITUDE;
_velocity = [[UIDynamicItemBehavior alloc] initWithItems:#[viewToAnimate]];
}
// referenceView is just the view on top of which we're doing our animation. E.g., it could be self.view of a view controller. viewToAnimate must be a subview of the reference view.
- (instancetype) initWithReferenceView: (UIView *) referenceView viewToAnimate: (UIView *) viewToAnimate andDistance: (CGFloat) distanceInPoints;
{
self = [super init];
if (self) {
AssertIf(distanceInPoints <= 0.0, #"Invalid distance: %f", _distanceInPoints);
_distanceInPoints = distanceInPoints;
[self setupWithReferenceView:referenceView andViewToAnimate:viewToAnimate];
[self setDirection:CGVectorMake(0.0, 1.0)];
}
return self;
}
- (instancetype) initWithReferenceView: (UIView *) referenceView viewToAnimate: (UIView *) viewToAnimate andFinalPoint: (CGPoint) animateToPoint;
{
self = [super init];
if (self) {
// Need to compute distance and direction.
CGVector direction = [Vector subFirst:[Vector fromPoint:animateToPoint] from:[Vector fromPoint:viewToAnimate.frameOrigin]];
SPASLogDetail(#"direction after subtraction: %#", NSStringFromCGVector(direction));
// Special case: No direction because same start and finish.
if (direction.dy + direction.dx == 0.0) {
_distanceInPoints = 0.0;
}
else {
direction = [Vector normalize:direction]; // vectorNormalize(direction);
_distanceInPoints = [Vector distanceFromPoint:viewToAnimate.frameOrigin toPoint:animateToPoint];
}
SPASLogDetail(#"finalPoint: %#, direction: %#, distance: %f", NSStringFromCGPoint(animateToPoint), NSStringFromCGVector(direction), _distanceInPoints);
[self setupWithReferenceView:referenceView andViewToAnimate:viewToAnimate];
[self setDirection:direction];
}
return self;
}
- (void) setInitialVelocity:(CGFloat)initialVelocity;
{
_initialVelocity = initialVelocity;
// Only positive speeds in the velocity are relevant. Negative speeds reduce the velocity, they don't go the other direction.
_linearVelocity =
CGPointMake(initialVelocity * fabs(_direction.dx),
initialVelocity * fabs(_direction.dy));
}
- (void) setAccelerationRate:(CGFloat)accelerationRate;
{
_accelerationRate = accelerationRate;
_gravityBehavior.magnitude = accelerationRate;
}
// I'm only doing left, right, up, down animations because of the problem of rotating the viewToAnimate. I'm not sure I'll ever have a case where I want a rotated animated view. (Hmmm. If I want to do some kind of continuous animation, arbitrary direction with non-rotated objects could be cool!)
- (void) setDirection:(CGVector)direction;
{
if (_collision) {
[_animator removeBehavior:_collision];
_collision = nil;
}
if (_distanceInPoints == 0.0) {
// Why bother?
SPASLogDetail(#"Zero distance");
return;
}
// 9/24/15; HACK
//_distanceInPoints += 1.5;
// Since we're doing vector operations with one of the init methods above, the following seems risky!
//AssertIf(direction.dy != 0.0 && direction.dy != -1.0 && direction.dy != 1.0, #"Invalid dy: %f", direction.dy);
//AssertIf(direction.dx != 0.0 && direction.dx != -1.0 && direction.dx != 1.0, #"Invalid dx: %f", direction.dx);
_direction = direction;
_gravityBehavior.gravityDirection = direction;
_collision = [[UICollisionBehavior alloc] initWithItems:#[self.viewToAnimate]];
_collision.collisionDelegate = self;
CGPoint startBoundary;
CGPoint endBoundary;
#define SMALL_VALUE 0.05
BOOL (^closeToZero)(CGFloat) = ^(CGFloat value) {
if (value > -SMALL_VALUE && value < SMALL_VALUE) {
return YES;
}
else {
return NO;
}
};
if (closeToZero(direction.dx)) {
// Vertical motion.
CGFloat yBoundary = direction.dy * _distanceInPoints + self.viewToAnimate.frameY;
if (direction.dy > 0.0) {
// If we're going down, then we need to add the height of the self.viewToAnimate to our boundary. This is because the origin coords are in the *upper*, left of the viewToAnimate.
yBoundary += self.viewToAnimate.frameHeight;
}
startBoundary = CGPointMake(self.viewToAnimate.frameX, yBoundary);
endBoundary = CGPointMake(self.viewToAnimate.frameX + self.viewToAnimate.frameWidth, yBoundary);
}
else {
// Horizontal motion.
CGFloat xBoundary = direction.dx * _distanceInPoints + self.viewToAnimate.frameX;
if (direction.dx > 0.0) {
// If we're going to the right, then we need to add the width of the self.viewToAnimate to our boundary. This is because the origin coords are in the upper, *left* of the viewToAnimate.
xBoundary += self.viewToAnimate.frameWidth;
}
startBoundary = CGPointMake(xBoundary, self.viewToAnimate.frameY);
endBoundary = CGPointMake(xBoundary, self.viewToAnimate.frameY + self.viewToAnimate.frameHeight);
}
SPASLog(#"startBoundary: %#, endBoundary: %#", NSStringFromCGPoint(startBoundary), NSStringFromCGPoint(endBoundary));
[_collision addBoundaryWithIdentifier:#"barrier"
fromPoint:startBoundary
toPoint:endBoundary];
[_animator addBehavior:_collision];
}
- (void) run;
{
if (_collision) {
[_animator addBehavior:_gravityBehavior];
[_velocity addLinearVelocity:_linearVelocity forItem:self.viewToAnimate];
[_animator addBehavior:_velocity];
}
else {
if (self.completion) {
self.completion();
}
}
}
#pragma mark - UIDynamicAnimatorDelegate methods
- (void)dynamicAnimatorDidPause:(UIDynamicAnimator*)animator;
{
if (self.completion) {
self.completion();
}
}
#pragma mark -
#pragma mark - UICollisionBehaviorDelegate methods
// This isn't the method that gets called in our case.
//- (void)collisionBehavior:(UICollisionBehavior*)behavior beganContactForItem:(id <UIDynamicItem>)item1 withItem:(id <UIDynamicItem>)item2 atPoint:(CGPoint)p;
- (void)collisionBehavior:(UICollisionBehavior*)behavior beganContactForItem:(id <UIDynamicItem>)item withBoundaryIdentifier:(id <NSCopying>)identifier atPoint:(CGPoint)p;
{
if (!_calledFirstImpactCallback) {
_calledFirstImpactCallback = YES;
if (self.firstImpactCallback) {
self.firstImpactCallback();
}
}
}
#pragma mark -
#end
I'm working in Swift, and I am seeing the same behavior as you do with 1.5 points offset. It seems to be unrelated to the resolution of the device (1x, 2x or 3x), all have 1.5 points offset.
However, using the the path-based API, the problem seems to not be there anymore:
let collisionBehavior: UICollisionBehavior = ...
let topLeft: CGPoint = ...
let bottomLeft: CGPoint = ...
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, topLeft.x, topLeft.y)
CGPathAddLineToPoint(path, nil, bottomLeft.x, bottomLeft.y)
let bezierPath = UIBezierPath(CGPath: path)
collisionBehavior.addBoundaryWithIdentifier("myID", forPath: bezierPath)
Converting this to Objective-C is easy enough:
UICollisionBehavior *collisionBehavior = ...
CGPoint topLeft = ...
CGPoint bottomLeft = ...
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, topLeft.x, topLeft.y);
CGPathAddLineToPoint(path, nil, bottomLeft.x, bottomLeft.y);
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithCGPath: path];
[collisionBehavior addBoundaryWithIdentifier: #"myID" forPath: path];

How to collapse an NSSplitView pane with animation while using Auto Layout?

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.

IBOutlet control is nil

I am trying to set text of a NSTextField from a different class..
This is what i have:
Preferences.h
#interface Preferences : NSObject
{
IBOutlet NSTextField *selectionPointX;
}
#property (nonatomic, unsafe_unretained) IBOutlet NSTextField *dateTimeFormatPreview;
- (void)getSelection:(NSPoint)point :(NSSize)size;
#end
Preferences.m (only what's needed)
#import "Preferences.h"
#implementation Preferences
NSUserDefaults *userDefaults = nil;
int cPx;
int cPy;
int cSw;
int cSh;
- (void)getSelection:(NSPoint)point :(NSSize)size{
cPx = (int) point.x;
cPy = (int) point.y;
cSw = (int) size.width;
cSh = (int) size.height;
[self saveSelection];
}
- (void)saveSelection{
NSPoint p;
p.x = cPx;
p.y = cPy;
NSSize s;
s.width = cSw;
s.height = cSh;
[userDefaults setObject:NSStringFromPoint(p) forKey:#"selectionPoint"];
NSLog(#"Saved Window Position: X: %i Y: %i", cPx, cPy);
[userDefaults setObject:NSStringFromSize(s) forKey:#"selectionSize"];
NSLog(#"Saved Window Size: W: %i H: %i", cSw, cSh);
[userDefaults synchronize];
[selectionPointX setIntegerValue:cPx]; // selectionPointX is nil
}
#end
I call getSelection from a different class, passing values to it.
In the Interface Builder, i have a NSObject with class Preferences, and from it i have connected the Outlet to the controller.
But when debugging selectionPointX is nil and so not updating my TextField.
I'm new to objective-c so probably i'm doing it wrong.
I have searched a lot but can't find a solution.
Any help appreciated, thank you.
EDIT: I think i have found the problem. Since i call the method from a different class, i create another instance of that class, and so all connections are not hooked up.
I did that:
Preferences *prefs = [[Preferences alloc] init];
[prefs getSelection:(NSPoint)wPos :(NSSize)wSize];
How i can call the same method, but using the current instance of Preferences that is loaded by the XIB?
I have a LocalSettingsController which is similiar to what you want here. In order to use the same Preferences instance all the time implement the Singleton pattern. Here's the code:
#implementation LocalSettingsController
+ (id)alloc
{
return self.sharedSettings;
}
+ (id)allocWithZone: (NSZone *)zone
{
return self.sharedSettings;
}
+ (instancetype)sharedSettings
{
static LocalSettingsController* singleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singleton = [[self localAlloc] localInit];
});
return singleton;
}
- (id)init
{
return self;
}
+ (id)localAlloc
{
return [super allocWithZone: NULL];
}
- (id)localInit
{
return [super init];
}
In code you can use the sharedSettings member, in IB you'd place an NSObject in your xib and change its instance type to LocalSettingsController (or in your case Preferences).

Creating an animatable translucent overlay with Core Animation layers

I'm creating a spotlight that moves over content in my app, like so:
In the sample app (shown above), the background layer is blue, and I have a layer over it that darkens all of it, except a circle that shows it normally. I've got this working (you can see how in the code below). In my real app, there is actual content in other CALayers, rather than just blue.
Here's my problem: it doesn't animate. I'm using CGContext drawing to create the circle (which is an empty spot in an otherwise black layer). When you click the button in my sample app, I draw the circle at a different size in a different location.
I would like that to smoothly translate and scale, instead of jumping, as it currently does. It may require a different method of creating the spotlight effect, or there might be a way I don't know of to implicitly animate the -drawLayer:inContext: call.
It's easy to create the sample app:
Make a new Cocoa app (using ARC)
Add the Quartz framework
Drop a custom view and a button onto the XIB
Link the custom view to a new class (SpotlightView), with code provided below
Delete SpotlightView.h, since I included its contents in SpotlightView.m
Set the button's outlet to the -moveSpotlight: action
Update (the mask property)
I like David Rönnqvist's suggestion in comments to use the mask property of the darkened layer to cut out a hole, which I could then move independently. The problem is that for some reason, the mask property works the opposite of how I expect a mask to work. When I specify a circular mask, all that shows up is the circle. I expected the mask to work in the opposite manner, masking out the area with 0 alpha.
Masking feels like the right way to go about this, but if I have to fill in the entire layer and cut out a hole, then I may as well do it the way I originally posted. Does anyone know how to invert the -[CALayer mask] property, so that the area drawn in gets cut out from the layer's image?
/Update
Here's the code for SpotlightView:
//
// SpotlightView.m
//
#import <Quartz/Quartz.h>
#interface SpotlightView : NSView
- (IBAction)moveSpotlight:(id)sender;
#end
#interface SpotlightView ()
#property (strong) CALayer *spotlightLayer;
#property (assign) CGRect highlightRect;
#end
#implementation SpotlightView
#synthesize spotlightLayer;
#synthesize highlightRect;
- (id)initWithFrame:(NSRect)frame {
if ((self = [super initWithFrame:frame])) {
self.wantsLayer = YES;
self.highlightRect = CGRectNull;
self.spotlightLayer = [CALayer layer];
self.spotlightLayer.frame = CGRectInset(self.layer.bounds, -50, -50);
self.spotlightLayer.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
self.spotlightLayer.opacity = 0.60;
self.spotlightLayer.delegate = self;
CIFilter *blurFilter = [CIFilter filterWithName:#"CIGaussianBlur"];
[blurFilter setValue:[NSNumber numberWithFloat:5.0]
forKey:#"inputRadius"];
self.spotlightLayer.filters = [NSArray arrayWithObject:blurFilter];
[self.layer addSublayer:self.spotlightLayer];
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {}
- (void)moveSpotlight:(id)sender {
[self.spotlightLayer setNeedsDisplay];
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
if (layer == self.spotlightLayer) {
CGContextSaveGState(ctx);
CGColorRef blackColor = CGColorCreateGenericGray(0.0, 1.0);
CGContextSetFillColorWithColor(ctx, blackColor);
CGColorRelease(blackColor);
CGContextClearRect(ctx, layer.bounds);
CGContextFillRect(ctx, layer.bounds);
// Causes the toggling
if (CGRectIsNull(self.highlightRect) || self.highlightRect.origin.x != 25) {
self.highlightRect = CGRectMake(25, 25, 100, 100);
} else {
self.highlightRect = CGRectMake(NSMaxX(self.layer.bounds) - 50,
NSMaxY(self.layer.bounds) - 50,
25, 25);
}
CGRect drawnRect = [layer convertRect:self.highlightRect
fromLayer:self.layer];
CGMutablePathRef highlightPath = CGPathCreateMutable();
CGPathAddEllipseInRect(highlightPath, NULL, drawnRect);
CGContextAddPath(ctx, highlightPath);
CGContextSetBlendMode(ctx, kCGBlendModeClear);
CGContextFillPath(ctx);
CGPathRelease(highlightPath);
CGContextRestoreGState(ctx);
}
else {
CGColorRef blueColor = CGColorCreateGenericRGB(0, 0, 1.0, 1.0);
CGContextSetFillColorWithColor(ctx, blueColor);
CGContextFillRect(ctx, layer.bounds);
CGColorRelease(blueColor);
}
}
#end
I finally got it. What prodded me to the answer was hearing of the CAShapeLayer class. At first, I thought it would be a simpler way to draw the layer's contents, rather than drawing and clearing the contents of a standard CALayer. But I read the documentation of the path property of CAShapeLayer, which stated it could be animated, but not implicitly.
While a layer mask might have been more intuitive and elegant, it doesn't seem to be possible to use the mask to hide a portion of the owner's layer, rather than showing a portion, and so I couldn't use it. I'm happy with this solution, as it's pretty clear what's going on. I wish it used implicit animation, but the animation code is only a few lines.
Below, I've modified the sample code from the question to add smooth animation. (I removed the CIFilter code, because it was extraneous. The solution does still work with filters.)
//
// SpotlightView.m
//
#import <Quartz/Quartz.h>
#interface SpotlightView : NSView
- (IBAction)moveSpotlight:(id)sender;
#end
#interface SpotlightView ()
#property (strong) CAShapeLayer *spotlightLayer;
#property (assign) CGRect highlightRect;
#end
#implementation SpotlightView
#synthesize spotlightLayer;
#synthesize highlightRect;
- (id)initWithFrame:(NSRect)frame {
if ((self = [super initWithFrame:frame])) {
self.wantsLayer = YES;
self.highlightRect = CGRectNull;
self.spotlightLayer = [CAShapeLayer layer];
self.spotlightLayer.frame = self.layer.bounds;
self.spotlightLayer.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
self.spotlightLayer.fillRule = kCAFillRuleEvenOdd;
CGColorRef blackoutColor = CGColorCreateGenericGray(0.0, 0.60);
self.spotlightLayer.fillColor = blackoutColor;
CGColorRelease(blackoutColor);
[self.layer addSublayer:self.spotlightLayer];
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {}
- (CGPathRef)newSpotlightPathInRect:(CGRect)containerRect
withHighlight:(CGRect)spotlightRect {
CGMutablePathRef shape = CGPathCreateMutable();
CGPathAddRect(shape, NULL, containerRect);
if (!CGRectIsNull(spotlightRect)) {
CGPathAddEllipseInRect(shape, NULL, spotlightRect);
}
return shape;
}
- (void)moveSpotlight {
CGPathRef toShape = [self newSpotlightPathInRect:self.spotlightLayer.bounds
withHighlight:self.highlightRect];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:#"path"];
pathAnimation.fromValue = (__bridge id)self.spotlightLayer.path;
pathAnimation.toValue = (__bridge id)toShape;
[self.spotlightLayer addAnimation:pathAnimation forKey:#"path"];
self.spotlightLayer.path = toShape;
CGPathRelease(toShape);
}
- (void)moveSpotlight:(id)sender {
if (CGRectIsNull(self.highlightRect) || self.highlightRect.origin.x != 25) {
self.highlightRect = CGRectMake(25, 25, 100, 100);
} else {
self.highlightRect = CGRectMake(NSMaxX(self.layer.bounds) - 50,
NSMaxY(self.layer.bounds) - 50,
25, 25);
}
[self moveSpotlight];
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
CGColorRef blueColor = CGColorCreateGenericRGB(0, 0, 1.0, 1.0);
CGContextSetFillColorWithColor(ctx, blueColor);
CGContextFillRect(ctx, layer.bounds);
CGColorRelease(blueColor);
}
#end

Why do I get different results when I run a program from testing trough Xcode and just taping the icon on the device?

I am having a really weird problem because i get completely different results between testing my program WHILE connected to the computer (trough xcode) but ON my device. and just taping the icon while not being plugged to xcode. (I think it might be coordinate issues).
So i was thinking there might be a difference between testing in these 2 ways.
Sorry i forgot to specify, I used to get the same results in both ways but then i created a singleton for my location manager instead of creating a single location manager object in each window.
This is how i am creating the Header:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
// protocol for sending location updates to another view controller
#protocol LocationManagerDelegate <NSObject>
#required
- (void)locationUpdate:(CLLocation*)location;
#end
#interface LocationManagerSingleton : NSObject <CLLocationManagerDelegate> {
CLLocationManager* locationManager;
CLLocation* location;
//id delegate;
}
#property (nonatomic, retain) CLLocationManager* locationManager;
#property (nonatomic, retain) CLLocation* location;
#property (nonatomic, assign) id <LocationManagerDelegate> delegate;
+ (LocationManagerSingleton*) sharedInstance; // Singleton method
#end
and this is the implementation:
#import "LocationManagerSingleton.h"
//static LocationManagerSingleton* sharedCLDelegate = nil;
#implementation LocationManagerSingleton
#synthesize locationManager, location, delegate;
#pragma mark - Singleton Methods -
+ (LocationManagerSingleton*)sharedInstance {
static LocationManagerSingleton *_sharedInstance;
if(!_sharedInstance) {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[super allocWithZone:nil] init];
});
}
return _sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
#if (!__has_feature(objc_arc))
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release {
//do nothing
}
- (id)autorelease {
return self;
}
#endif
#pragma mark - Custom Methods -
// Add your custom methods here
- (id)init
{
self = [super init];
if (self != nil) {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
self.locationManager.distanceFilter = 5;
self.locationManager.purpose = #"This app uses your location for Augmented Reality";
[self.locationManager startUpdatingLocation];
[self.locationManager startUpdatingHeading];
NSLog(#"LocationManager initialized with accuracy best for Navigation");
NSLog(#"CUrrent Latitude: %f, Current Longitude: %f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude);
}
return self;
}
#pragma mark - CLLocationManagerDelegate Methods -
- (void)locationManager:(CLLocationManager*)manager
didUpdateToLocation:(CLLocation*)newLocation
fromLocation:(CLLocation*)oldLocation
{
/*…some filer method to check if the new location is good …*/
bool good = YES;
if (good)
{
[self.delegate locationUpdate:newLocation];
}
//self.location = newLocation;
//NSLog(#"Updated: %#",newLocation);
}
- (void)locationManager:(CLLocationManager*)manager
didFailWithError:(NSError*)error
{
/* ... */
}
#end
Okay it seems that OpenGL was causing the problem. My theory was that since a pointer variable used for texturing was inside a loop when the localization manager updated and redraw this variable would get messed up because it was being reinitialized everyrun but the value wouldnt be set to 0, and since opengl has the pointer to the adress not to the pointer it would read corrupted data (since the loop might have updated that space until opengl was told the new adress of the variable). Still i have no idea why it worked perfectly while hooked up to the computer and not by itself.

Resources