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

标签 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
  }
}

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

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

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

最佳答案

同一类中的调用方法是通过隐含的 self 进行调用的。在这种情况下,由于闭包,您必须明确说明:

self.animateButton(aButton, step: 1)

关于swift - 在 Swift 调用 animateWithDuration :Animations: 中捕获函数参数时出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430026/

相关文章:

javascript - 从 .then 函数分配到更高级别的作用域变量是否存在任何陷阱

uiview - 在 Swift 2 中设置 animateWithDuration 中的选项

ios - 如何在 iOS 中创建具有更好性能的复杂动画?

swift - 提取字典的值

ios - 在类中定义的闭包中到达 "self"

ios - PageMenu 如何动态(以编程方式)添加 View Controller ?

ios - 在 Swift 2 中创建异步任务

watchkit - animateWithDuration 缺少完成 block ,WatchOS 2

ios - 当一个对象的属性同时被另外两个对象设置时,CPU 会达到 %100

swift - 将鼠标保持在 Swift 的区域内