问题描述
我在情节提要中使用自动布局设置了square
NSButton
。
该按钮设置为Image only
,我使用NSRefreshTemplate
系统映像。
这是我使其旋转的代码
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"];
}
}
在我在Xcode 12.2
上使用新的MacOS 11.0
beta版之前,此方法一直工作良好。现在按钮旋转似乎不再居中。
如果将按钮Scaling
设置为None
,它将在中心旋转,但是图像太小。如果我将Scaling
设置为Proportionately Up or Down
,以便图像填充按钮,则图像旋转会很奇怪。
我该如何解决?
解决方法
问题
在Catalina上,即使在Xcode 12 beta上它仍然可以使用。问题似乎是,在macOS 11 Big Sur中,按钮不再居中对齐。
可以这样测试:
button.image = [NSImage imageNamed:NSImageNameRefreshTemplate];
[button.cell setBackgroundColor:NSColor.redColor];
在Catalina上,按钮居中对齐的情况与此不同。也许这是Big Sur中的错误,将在即将发布的版本中修复。对于这两种变体,我都使用Xcode 12.2 beta2。因此它与操作系统有关,而不与Xcode beta有关。
解决方法
以集中对齐的方式绘制刷新图标,然后使用自定义图标,例如
button.image = [NSImage imageNamed:@"my_refresh_icon"];
然后,动画在Catalina上以及在macOS Big Sur上同样有效。
测试