将视图的alpha设置为0到0.5

时间:2014-10-05 13:45:42

标签: objective-c cocoa animation nsview alpha

我创建一个NSView作为叠加视图。在将其添加为另一个视图的子视图后,我想将其alpha值从0设置为0.5。我正在做以下事情,但我从来没有看到视图的alpha动画为0.5。我知道视图已被正确添加,因为我看到它,如果我将它设置为backgroundcolor以具有完整的alpha。我在这里错过了一些简单的东西吗?

self.overlayView = [[MyOverlayView alloc] initWithFrame:frameRect];
self.overlayView.layer.backgroundColor = CGColorCreateGenericRGB(0., 0., 0., 0.0);
[self.window.contentView addSubview:self.overlayView];

__typeof__(self) __weak weakSelf = self;
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
     context.duration = 1;
     weakSelf.overlayView.animator.alphaValue = 0;
}
     completionHandler:^{
         weakSelf.overlayView.alphaValue = 0.5;
}];

我也尝试过这样的事情:

[[self.overlayView animator] setAlphaValue:1.0];

2 个答案:

答案 0 :(得分:3)

您需要将 wantsLayer 设置为YES。背景颜色的alpha值也应为1.0而不是0.0。

self.overlayView = [[MyOverlayView alloc] initWithFrame:frameRect];
self.overlayView.wantsLayer=YES;
self.overlayView.layer.backgroundColor = CGColorCreateGenericRGB(0., 0., 0., 1.0);
[self.window.contentView addSubview:self.overlayView];

__typeof__(self) __weak weakSelf = self;
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
     context.duration = 1;
     weakSelf.overlayView.animator.alphaValue = 0;
}
     completionHandler:^{
         weakSelf.overlayView.alphaValue = 0.5;
}];

答案 1 :(得分:0)

要制作动画的视图上需要wantsLayer,还需要animator代理对象

let textField = NSTextField()
textField.wantsLayer = true

NSAnimationContext.runAnimationGroup({ context in
  context.duration = 1.0

  textField.stringValue = "\(emoji.visual) copied to clipboard"
  textField.animator().alphaValue = 1.0
}, completionHandler: {
   self.textField.alphaValue = 0.0
})