应用响应时在Xcode-Swift中呼吸动画

Sim*_*zon 0 xcode uiviewanimation ios dispatch-async swift

我正在尝试使恒星“呼吸”在一个循环中。变大然后变小,然后重复。我希望在我的应用程序仍在运行并响应时继续执行此操作。当我在应用程序中转到另一个视图时,我希望动画停止播放。

这就是我得到的

    override func viewDidLoad() {
    super.viewDidLoad()

    DispatchQueue.main.async {
            self.animateStars()
    }
}

func animateStars() {
  UIView.animate(withDuration: 4, animations : {
        self.star.transform = CGAffineTransform(scaleX: 2.5, y: 2.5)

    }) { finished in
        NSLog("Star is big. Finished = \(finished)")
    }

    UIView.animate(withDuration: 4, animations : {
        self.star.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)

    }) { finished in
        NSLog("Star is small. Finished = \(finished)")
    }
}
Run Code Online (Sandbox Code Playgroud)

这并不困难。而且,我不知道如何在用户单击带有segue的按钮时不让它在后台疯狂运行的情况下使其循环。

我在Objective C中找到了一种解决方案,但是我似乎无法理解如何将其转换为Swift 3.0。此处的示例:https : //stackoverflow.com/a/31978173/5385322

 [UIView animateWithDuration:1
                  delay:0
                options:UIViewKeyframeAnimationOptionAutoreverse | UIViewKeyframeAnimationOptionRepeat
             animations:^{
                 yourView.transform = CGAffineTransformMakeScale(1.5, 1.5);
             }
             completion:nil];
Run Code Online (Sandbox Code Playgroud)

感谢您的时间和建议!//西蒙

Dun*_*n C 5

您发布的Objective-C重复动画代码的Swift版本将是:

UIView.animate(withDuration: 1.0,
               delay: 0,
               options: [.autoreverse, .repeat, .allowUserInteraction],
               animations: {
                self.star.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
},
               completion: nil

)
Run Code Online (Sandbox Code Playgroud)

(在Swift中,大多数选项标志参数(例如该options动画代码中的参数)的类型均为OptionSet,是支持Swift Set语法的位标志,因此您可以在方括号中列出所需的选项,并用逗号分隔。

请注意,@ TungFam的解决方案无法按书面方式工作,但如果您使用完成块检查animate布尔值并重新调用animation方法(如果为true),则可以使用该方法。

编辑:

如果要停止动画,请使用

self.star.layer.removeAllAnimations()
self.star.layer.transform = CGAffineTransform.identity
Run Code Online (Sandbox Code Playgroud)

编辑#2:

如果您希望能够随意启动和停止动画,则可以使用如下代码:

func animateView(_ view: UIView, animate: Bool) {
  if animate {
    UIView.animate(withDuration: 1.0,
                   delay: 0,
                   options: [.autoreverse, .repeat, .allowUserInteraction],
                   animations: {
                    view.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
    },
                   completion: nil

    )
  } else {
    self.button.layer.removeAllAnimations()
    UIView.animate(withDuration: 1.0,
                   delay: 0,
                   options: [.curveEaseOut, .beginFromCurrentState, .allowUserInteraction],
                   animations: {
                    view.transform = CGAffineTransform.identity
    },
                   completion: nil

    )
  }
}
Run Code Online (Sandbox Code Playgroud)

当停止动画时,该代码将使视图平滑地恢复为正常大小。它还将在动画中添加.allowUserInteraction标志,以防您正在动画的视图是您希望能够在其大小更改时点击的按钮。