Whats the Swift animate WithDuration syntax?

前端 未结 4 818
夕颜
夕颜 2020-12-01 10:29

I\'m porting an older app over to Xcode 7 beta and I\'m getting an error on my animations:

Cannot invoke \'animateWithDuration\' with an argument list

相关标签:
4条回答
  • 2020-12-01 10:45

    Swift 3/4 Syntax

    Here's an update with the Swift 3 Syntax:

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

    If you need to add a completion handler just add a closure like so:

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

    Old Answer:

    It turns out it's a very simple fix, just change options: nil to options: [].

    Swift 2.2 Syntax:

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

    What changed?

    Swift 2 got rid of the C-Style comma-delimited list of options in favor of option sets (see: OptionSetType). In my original question, I passed in nil for my options, which was valid prior to Swift 2. With the updated syntax, we now see an empty option list as an empty set: [].

    An example of animateWithDuration with some options would be this:

     UIView.animateWithDuration(0.5, delay: 0.3, options: [.Repeat, .CurveEaseOut, .Autoreverse], animations: {
          self.username.center.x += self.view.bounds.width
        }, completion: nil)
    
    0 讨论(0)
  • 2020-12-01 10:47

    Swift 3 Syntax with completion block

    UIView.animate(withDuration: 3.0 , delay: 0.25, options: .curveEaseOut, animations: {
    
            // animation
        }, completion: { _ in
    
            // completion
        })
    
    0 讨论(0)
  • 2020-12-01 10:58

    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)
    
    0 讨论(0)
  • 2020-12-01 11:07

    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
    })
    
    0 讨论(0)
提交回复
热议问题