什么是Swift 3 animateWithDuration语法?

Dan*_*ieu 31 animatewithduration swift swift2 optionsettype swift3

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

无法使用类型'(Double,delay:Double,options:nil,animations :() - > _,completion:nil)的参数列表调用'animateWithDuration'

这是代码:

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

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

什么是animateWithDuration的Swift 3语法?

Dan*_*ieu 66

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)
Run Code Online (Sandbox Code Playgroud)

如果你需要添加一个完成处理程序,只需添加一个闭包,如下所示:

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

旧答案:

事实证明这是一个非常简单的修复,只需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)
Run Code Online (Sandbox Code Playgroud)

改变了什么?

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)
Run Code Online (Sandbox Code Playgroud)

  • 他们在Swift 3中改变了很多东西,这使得在这个时候学习Swift变得非常困难. (3认同)

emr*_*raz 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)
Run Code Online (Sandbox Code Playgroud)