I have a square
NSButton
set using auto layout in a storyboard.
The button is set as Image only
and I use the NSRefreshTemplate
system image.
This is my code to made it spin
static BOOL _animate = NO;
- (void)animateRefreshButton:(BOOL)animate
{
NSButton *btn = _refreshButton;
[btn setWantsLayer:YES];
// Set the anchor point of the refresh button
CALayer *btnLayer = btn.layer;
NSRect frame = btn.frame;
btnLayer.position = NSMakePoint(NSMidX(frame), NSMidY(frame)); // position to centre of frame
btnLayer.anchorPoint = NSMakePoint(0.5, 0.5); // anchor point to centre - specified in unit coordinates
_animate = animate;
if (animate)
{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.delegate = self;
animation.fromValue = [NSNumber numberWithFloat:2 * M_PI];
animation.toValue = [NSNumber numberWithFloat:0];
animation.duration = 0.6; // Speed
animation.repeatCount = 1;// INFINITY; // Repeat forever. Can be a finite number.
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[btn.layer addAnimation:animation forKey:@"refreshbutton.rotation"];
}
}
This has been working fine until I build with the new Xcode 12.2
beta on MacOS 11.0
. Now the buttons spin doesn't seem to be central.
If I set the button Scaling
to None
it will spin centrally fine but the image is far too small. If I set the Scaling
to Proportionately Up or Down
so the image fills the button, it spins weird.
How can I fix this?
Problem
On Catalina it still works even with Xcode 12 beta. Problem seems to be, that with macOS 11 Big Sur the button is no longer centrally aligned.
That can be tested like this:
button.image = [NSImage imageNamed:NSImageNameRefreshTemplate];
[button.cell setBackgroundColor:NSColor.redColor];
This is different on Catalina, where the button is centrally aligned. Maybe this is a bug in Big Sur that will be fixed in an upcoming version. For both variants I used Xcode 12.2 beta 2. So it related to the OS and not Xcode beta.
Workaround
Draw a refresh icon in a centrally aligned way and use your custom icon, e.g.
button.image = [NSImage imageNamed:@"my_refresh_icon"];
Then the animation works as well on Catalina as on macOS Big Sur.
Test