【问题标题】:Animate NSImageView translation动画 NSImageView 翻译
【发布时间】:2017-08-25 10:35:36
【问题描述】:

我正在尝试为 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)

【问题讨论】:

    标签: swift animation core-animation appkit


    【解决方案1】:

    如果您使用自动布局,您可以将outlet 添加到您的约束之一,并通过animator 更改constant 值。

    示例

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

    标签有两个约束。

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

    我现在可以在文档大纲中找到“到底部的距离”插座

    然后按 ctrl 将它拖到我对应的 NSViewController 那里我为它创建一个 outlet

    @IBOutlet weak var distanceToBottom: NSLayoutConstraint!
    

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

    最后一步是为视图设置动画。在这里,我只是在NSButton 上使用IBAction,如下所示:

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

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

    希望对你有所帮助。

    【讨论】:

    • 谢谢!我已经设法使用它的顶部约束为我的图像设置动画。
    • @JasonSuave 不客气,很高兴你成功了。一旦你发现你可以为约束添加出口......它只会让动画和自动布局更容易,对吧? :)