INFORMATIKER IM ALL
INFORMATIKER IM ALL

Reputation: 51

How to add a completion to an animation?

Hey I want to create a set game app, and now I want my cards(UIViews) move to a newPosition. after the animation ended I want this view to remove from super view

   func btnUp(card: CardSubview, frame: CGRect) {

        let newPosition = CGRect(x: (self.superview?.frame.minX)!, y: (self.superview?.frame.maxY)!, width: card.bounds.width, height: card.bounds.height)
        //UIView.animate(withDuration: 3.0, animations: {card.frame = newPosition})
        UIView.animate(withDuration: 3.0, animations: {card.frame = newPosition}, completion: {if card.frame == newPosition {card.removeFromSuperview()}})

    }

this is working but If I want to add a completion I get this error:

Cannot convert value of type '() -> ()' to expected argument type '((Bool) -> Void)?'**

so what am I doin wrong ?

Upvotes: 2

Views: 292

Answers (3)

Vivek Kumar
Vivek Kumar

Reputation: 406

UIView.animate(withDuration: 0.25, animations: {
   view.transform = CGAffineTransform(translationX: view.frame.maxX, y: 0)
},completion:{(completed:Bool) in
   if(completed){view.removeFromSuperview()}
})

Upvotes: 0

Harshal Valanda
Harshal Valanda

Reputation: 5451

Try this:

You need to set completion block variable

func btnUp(card: CardSubview, frame: CGRect) {

    let newPosition = CGRect(x: (self.superview?.frame.minX)!, y: (self.superview?.frame.maxY)!, width: card.bounds.width, height: card.bounds.height)
    //UIView.animate(withDuration: 3.0, animations: {card.frame = newPosition})
    UIView.animate(withDuration: 3.0, animations: {
        card.frame = newPosition
        }, completion: { finish in
             if card.frame == newPosition {card.removeFromSuperview()

        }})
}

Upvotes: 1

Nerkyator
Nerkyator

Reputation: 3976

Apple documentation says:

completion

A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called.

So you need to give that boolean argument to completion handler:

UIView.animate(withDuration: 3.0, animations: {card.frame = newPosition}, completion: { finish in
    if card.frame == newPosition {
         card.removeFromSuperview()
    }
})

Upvotes: 0

Related Questions