动画NSImageView转换

时间:2017-08-25 10:35:37

标签: swift animation core-animation appkit

我试图为NSImageView设置动画,使其在向下滑动几个点并淡入淡出。 经过几个小时的搜索,我只能设法获得动画的alpha值。 翻译视图有效,但它没有动画,我无法弄清楚原因。

import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var logo: NSImageView!
    @IBAction func doAnimation(_ sender: Any) {

        animateLogo()

    }

    private func animateLogo() {
        let top = CATransform3DMakeTranslation(0, 30, 0)
        logo.wantsLayer = true

        NSAnimationContext.runAnimationGroup({ (context) in
            Swift.print("Running animation")
            context.duration = 5
            logo.animator().alphaValue = 0

            logo.layer?.transform = top
        }, completionHandler: {
            Swift.print("Finished animation")
        })
    }

}

我在翻译NSView时尝试过的另一种方法是

logo.animator().translateOrigin(to: new_origin)

1 个答案:

答案 0 :(得分:1)

如果您使用自动布局,则可以为其中一个约束添加outlet,并通过constant更改animator值。

实施例

这里我有一个带标签和按钮的视图

My view

标签有两个约束条件。

  • 它在视图中水平居中
  • 视图底部的距离为80

我现在可以找到距离底部的距离"文件大纲中的出口

this guy

然后按住Ctrl键将其拖动到我为其创建NSViewController的相应outlet

@IBOutlet weak var distanceToBottom: NSLayoutConstraint!

我可以通过查看屏幕右侧的Connections Inspector来验证是否设置了outlet

enter image description here

最后一步是为视图设置动画。我只是在IBAction上使用NSButton,就像这样:

@IBAction func animate(_ sender: NSButton) {
    distanceToBottom.animator().constant = 5
}

如果我运行,我的标签会很好地动画到距离底部5个像素的新位置。

final result

希望对你有所帮助。

相关问题