在Swift中捕获函数参数时出现奇怪的错误调用animateWithDuration:动画:

时间:2015-05-25 01:06:46

标签: swift closures animatewithduration

我正在编写一些简单的动画代码,使按钮变得更高,然后使用UIView动画缩短。代码有点长,但相当简单:

func animateButton(aButton: UIButton, step: Int)
{
  let localStep = step - 1

  let localButton = aButton
  let halfHeight = aButton.bounds.height / 2

  var transform: CGAffineTransform
  switch step
  {
  case 2:
    //Make the center of the grow animation be the bottom center of the button
    transform = CGAffineTransformMakeTranslation(0, -halfHeight)

    //Animate the button to 120% of it's normal height.
    transform = CGAffineTransformScale( transform, 1.0, 1.2)
    transform = CGAffineTransformTranslate( transform, 0, halfHeight)
    UIView.animateWithDuration(0.5, animations:
      {
        aButton.transform = transform
      },
      completion:
      {
        (finshed) in
        //------------------------------------
        //--- This line throws the error ---
        animateButton(aButton, step: 1)
        //------------------------------------
    })
  case 1:
    //In the second step, shrink the height down to .25 of normal
    transform = CGAffineTransformMakeTranslation(0, -halfHeight)

    //Animate the button to 120% of it's normal height.
    transform = CGAffineTransformScale( transform, 1.0, 0.25)
    transform = CGAffineTransformTranslate( transform, 0, halfHeight)
    UIView.animateWithDuration(0.5, animations:
      {
        aButton.transform = transform
      },
      completion:
      {
        (finshed) in
        animateButton(aButton, step: 0)
    })
  case 0:
    //in the final step, animate the button back to full height.
    UIView.animateWithDuration(0.5)
      {
        aButton.transform = CGAffineTransformIdentity
    }
  default:
    break
  }
}

动画方法的完成块是闭包。我收到错误"在闭包中调用方法animateButton需要使用显式self.来明确捕获语义。

问题是,参数aButton是封闭函数的参数。没有引用实例变量。

在我看来这是编译器错误。我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:1)

使用隐含的self调用同一类中的调用方法。在这种情况下,由于关闭,你必须明确:

self.animateButton(aButton, step: 1)