Swift animate WithDuration 语法是什么?

Whats the Swift animate WithDuration syntax?

我正在将一个较旧的应用程序移植到 Xcode 7 beta,但我的动画出现错误:

Cannot invoke 'animateWithDuration' with an argument list of type '(Double, delay: Double, options: nil, animations: () -> _, completion: nil)'

代码如下:

 UIView.animateWithDuration(0.5, delay: 0.3, options: nil, animations: {
      self.username.center.x += self.view.bounds.width
    }, completion: nil)

这在 Xcode 6 中有效,所以我假设这是 Swift 中的更新。所以我的问题是:

animateWithDuration 的 Swift3 语法是什么?

Swift 3/4 语法

这是 Swift3 语法的更新:

UIView.animate(withDuration: 0.5, delay: 0.3, options: [.repeat, .curveEaseOut, .autoreverse], animations: {
    self.username.center.x += self.view.bounds.width
}, completion: nil)

如果您需要添加一个完成处理程序,只需像这样添加一个闭包:

UIView.animate(withDuration: 0.5, delay: 0.3, options: [.repeat, .curveEaseOut, .autoreverse], animations: {
    // animation stuff      
}, completion: { _ in
    // do stuff once animation is complete
})

旧答案:

事实证明这是一个非常简单的修复,只需将 options: nil 更改为 options: []

Swift 2.2 语法:

UIView.animateWithDuration(0.5, delay: 0.3, options: [], animations: {
      self.username.center.x += self.view.bounds.width
    }, completion: nil)

有什么变化?

Swift 2 去掉了 C-Style 逗号分隔的选项列表,取而代之的是选项集(参见:OptionSetType)。在我原来的问题中,我为我的选项传入了 nil,它在 Swift 之前有效 2. 使用更新的语法,我们现在看到一个空选项列表作为一个空集:[].

带有一些选项的 animateWithDuration 示例如下:

 UIView.animateWithDuration(0.5, delay: 0.3, options: [.Repeat, .CurveEaseOut, .Autoreverse], animations: {
      self.username.center.x += self.view.bounds.width
    }, completion: nil)

Swift 3, 4, 5

UIView.animate(withDuration: 1.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
    cell.transform = CGAffineTransform(translationX: 0, y: 0)
}, completion: nil)

Swift 3 带完成块的语法

UIView.animate(withDuration: 3.0 , delay: 0.25, options: .curveEaseOut, animations: {

        // animation
    }, completion: { _ in

        // completion
    })

Swift 2

UIView.animateWithDuration(1.0, delay: 0.1, options: [.Repeat, .CurveEaseOut, .Autoreverse], animations: {
    // animation
}, completion: { finished in
    // completion
})

Swift 3, 4, 5

UIView.animate(withDuration: 1.0, delay: 0.1, options: [.repeat, .curveEaseOut, .autoreverse], animations: {
    // animation
}, completion: { finished in
    // completion
})