ios - 如何创建一系列函数并在 Swift 中循环它们?

标签 ios loops swift

我正在尝试构建一个功能,以便当你摇动 iPhone 时,屏幕上的颗粒会飞来飞去。

当摇晃开始和结束时,我可以系上钩子(Hook)。

我将创建一个 UIPushBehavior 并将其添加到动画师场景中,当晃动开始时,当晃动结束时,我将从动画师中删除 UIPushBehavior。

但为了获得良好的摇动体验,我想在设备运动时改变插入角度。

如何在 Swift 中重新创建此伪代码?

override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent!)
{
    if (motion == UIEventSubtype.MotionShake)
    {
        self.push = UIPushBehavior()
        self.push!.angle = -self.angle!
        self.animator.addBehavior(self.push)
        // BEGIN Pseudo Code
        self.sequence = Sequence({self.push.angle = self.angle!}, {self.push.angle = -self.angle}, 
        delay: 100ms)
       // END Pseudo Code
    }
}

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent!)
{
    if (motion == UIEventSubtype.MotionShake)
    {

       self.animator.removeBehavior(self.push)
       // BEGIN Pseudo Code
       self.sequence.stopSequence()
       // END Pseudo Code
    }
}

正如你所看到的,我希望能够定义 2 个函数(将插入角度的方向改变 180 度)每 100 毫秒循环一次,直到我调用 stopSequence()

我怎样才能用 Swift 做到这一点?

最佳答案

您是否正在寻找这样的东西:

class MySequence {
  var functions : Array<() -> ()>

  func runSequenceOneTime () -> Void {
    for function in functions {
      function ()
    }
  }

  func stopSequence () -> Void {
    // uninstall alarm
  }

  func startSequence (delay: Double) -> Void {
    // install alarm w/ runSequenceOneTime
  }

  init (delay: Double, _ functions: (() -> ())...) {
    self.functions = functions
    self.startSequence (delay)
  }
}

然后您将创建一个 MySequence 实例,如下所示:

var mySeq = MySequence (delay: 0.1, func1, func2, func3)

关于ios - 如何创建一系列函数并在 Swift 中循环它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24234785/

相关文章:

java - 改进两次遍历数组(同一数组上的嵌套循环)

swift - FirebaseobserveSingleEvent 崩溃应用程序?出现错误 "URL scheme must be one of gs://, http://, or https://"

swift - SpriteKit : Add SKSpriteView To The View

ios - 在背景中使用与主要 UIImage 颜色相同的颜色覆盖 UIView

ios - 模拟器看起来与 Storyboard屏幕上的布局不同

ios - yarn 运行 ios - 错误 : Cannot find module - React Native

ios - "UIImage imageWithContentsOfFile"在动画数组中不工作,我需要它来减少内存

c - 进入无限循环的简单 C 代码。为什么?

ios - 如何用swift添加一个圆形按钮?

python - 更好/更快地循环遍历集合或列表?