37

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

无法使用类型为“(Double,延迟:Double,选项:nil,动画:()-> _,完成:nil)”的参数列表调用“animateWithDuration”

这是代码:

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

这适用于 Xcode 6,所以我假设这是 Swift 中的更新。所以我的问题是:

animateWithDuration 的 Swift 3 语法是什么?

4

4 回答 4

70

Swift 3/4 语法

这是 Swift 3 语法的更新:

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: niloptions: [].

斯威夫特 2.2 语法:

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

发生了什么变化?

Swift 2 摆脱了 C 风格的以逗号分隔的选项列表,转而支持选项集(参见: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)
于 2015-06-23T00:58:01.490 回答
6

斯威夫特 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)
于 2016-09-28T08:59:45.030 回答
4

带有完成块的 Swift 3 语法

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

        // animation
    }, completion: { _ in

        // completion
    })
于 2017-03-23T07:53:01.133 回答
0

斯威夫特 2

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

斯威夫特 3, 4, 5

UIView.animate(withDuration: 1.0, delay: 0.1, options: [.repeat, .curveEaseOut, .autoreverse], animations: {
    // animation
}, completion: { finished in
    // completion
})
于 2019-07-27T07:34:22.790 回答