简体   繁体   中英

UIView.animateWithDuration in Swift 2.0

I am new to programming and am trying to learn Swift and Xcode with the help of the book "Swift for Beginners: Develop and Design". The book has been helpful so far and I have learned a lot already, however, it seems that Swift and Xcode have been updated since the book came out and that has led to some changes.

I am currently trying to code the sample memory game in Chapter 9, and I've run into a problem. Up until now, any differences caused by an updated version of Swift I have been able to figure out on my own, but this one is stumping me.

The code causing the error is this:

UIView.animateWithDuration(highlightTime,
    delay: 0.0,
    options: [.CurveLinear, .AllowUserInteraction, .BeginFromCurrentState],
    animations: {
        button.backgroundColor = highlightColor
    }, completion: { finished in
        button.backgroundColor = originalColor
        var newIndex : Int = index + 1
        self.playSequence(newIndex, highlightTime:  highlightTime)
})

The error message is this:

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

And the suggestion is this:

Expected an argument list of type '(NSTimeInterval, delay: NSTimeInterval, options: UIViewAnimationOptions, animations: () -> Void, completion: ((Bool) -> Void)?)'

Any help or insight would be appreciated.

Swift is picky with casting, so wrap the numbers in NSTimeInterval

UIView.animateWithDuration(NSTimeInterval(highlightTime),
    delay: NSTimeInterval(0.0),
    options: [.CurveLinear, .AllowUserInteraction, .BeginFromCurrentState],
    animations: {
        button.backgroundColor = highlightColor
    }, completion: { finished in
        button.backgroundColor = originalColor
        var newIndex : Int = index + 1
        self.playSequence(newIndex, highlightTime:  highlightTime)
})

It seems like your highlightTime is defined as some other type not as Double, while defining the variable, simply define its type as,

let highlightTime: Double = 1.0

And, that should fix it.

Thanks for the feedback, everyone.

After some time, I was able to figure it out.

I had previously declared the highlightTime variable as "highlightTime: Double", with no value assigned. I changed it to "highlightTime: NSTimeInterval" and it is working now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM