Break a loop inside an animation block - ios

I'm trying to break a for-loop after a completed UIView animation. Here is the following snippet:
public func greedyColoring() {
let colors = [UIColor.blue, UIColor.green, UIColor.yellow, UIColor.red, UIColor.cyan, UIColor.orange, UIColor.magenta, UIColor.purple]
for vertexIndex in 0 ..< self.graph.vertexCount {
let neighbours = self.graph.neighborsForIndex(vertexIndex)
let originVertex = vertices[vertexIndex]
print("Checking now Following neighbours for vertex \(vertexIndex): \(neighbours)")
var doesNotMatch = false
while doesNotMatch == false {
inner: for color in colors{
UIView.animate(withDuration: 1, delay: 2, options: .curveEaseIn, animations: {
originVertex.layer.backgroundColor = color.cgColor
}, completion: { (complet) in
if complet {
let matches = neighbours.filter {
let vertIdx = Int($0)!
print("Neighbour to check: \(vertIdx)")
let vertex = self.vertices[vertIdx-1]
if vertex.backgroundColor == color{
return true
}else{
return false
}
}
//print("there were \(matches.count) matches")
if matches.count == 0 {
// do some things
originVertex.backgroundColor = color
doesNotMatch = true
break inner
} else {
doesNotMatch = false
}
}
})
}
}
}
}
Basically this method iterate over a Graph and checks every vertex and its neighbours and give the vertex a color that none of its neighbours has. Thats why it has to break the iteration at the first color that hasn't been used. I tried to use Unlabeled loops but it still doesn't compile (break is only allowed inside a loop). The problem is that I would like to visualise which colors have been tested. Thats why I'm using the UIView.animate()
Is there anyway to solve my problem?

You need to understand, that the completion block that you pass to the animate function is called after the animation has finished, which is a long time (in computer time) after your for loop has iterated through the colors array. You set the duration to be 1 second, which means that the completion is called 1 second later. Since the for loop isn't waiting for your animation to finish, they will all start animating at the same time (off by some milliseconds perhaps). The for loop has completed way before the animation has completed, which is why it doesn't make sense to break the for loop, since it is no longer running!
If you want to see this add a print("Fire") call right before the UIView.animate function is called and print("Finished") in the completion block. In the console you should see all the fire before all the finished.
You should instead queue the animations, so that they start and finish one after the other.

As Frederik mentioned, the animations the order in execution of the next in your for loop is not synchronous with the order of your completions. This means that the for loop will keep cycling no matter of your blocks implementations.
An easy fix would be to create the animations by using CABasicAnimation and CAAnimationGroup. So that the product of your for loop would be a chain of animations stacked in an animation group.
This tutorial will give you an idea on how to use CABasicAnimation and CAAnimationGroup: https://www.raywenderlich.com/102590/how-to-create-a-complex-loading-animation-in-swift
You can use this approach, because the condition to break your for loop is given by parameters that are not dependent by the animation itself. The animations will be executed anyway once they will be attached to the view you are trying to animate.
Hope this helps.

Just modifying your code a little bit. Its a old school recursion but should work. Assuming all the instance variables are available here is a new version.
public func greedyColoring(vertex:Int,colorIndex:Int){
if vertexIndex > self.graph.vertexCount { return }
if colorIndex > color.count {return}
let neighbours = self.graph.neighborsForIndex(vertexIndex)
let originVertex = vertices[vertexIndex]
let color = self.colors[colorIndex]
UIView.animate(withDuration: 1, delay: 2, options: .curveEaseIn, animations: {
originVertex.layer.backgroundColor = color.cgColor
}, completion: { (complet) in
if complet {
let matches = neighbours.filter {
let vertIdx = Int($0)!
print("Neighbour to check: \(vertIdx)")
let vertex = self.vertices[vertIdx-1]
//No idea what you are trying to do here. So leaving as it is.
if vertex.backgroundColor == color{
return true
}else{
return false
}
}
//print("there were \(matches.count) matches")
if matches.count == 0 {
// do some things
originVertex.backgroundColor = color
greedyColoring(vertex: vertex++,colorIndex:0)
} else {
greedyColoring(vertex: vertex,colorIndex: colorIndex++)
}
}
})
}
Now we can call this function simply
greedyColor(vertex:0,colorIndex:0)

As mentioned before, the completion blocks are all called asynchronously, and thus do not exist within the for loop. Your best bet is to call a common method from within the completion blocks which will ignore everything after the first call.
var firstMatch: UIColor?
func foundMatch (_ colour: UIColor)
{
if firstMatch == nil
{
firstMatch = colour
print (firstMatch?.description ?? "Something went Wrong")
}
}
let colours: [UIColor] = [.red, .green, .blue]
for colour in colours
{
UIView.animate(withDuration: 1.0, animations: {}, completion:
{ (success) in
if success { foundMatch (colour) }
})
}

Related

is it possible to combine two animations in Lottie framwork

swift version is 5 and lottie version is 3.1.1
I want to show two animations Json file with Lottie, that way fade in first animation and after it done it fades out and the another one fades in and I have to take a loop and do it on an infinity loop.
boardAnimationViewForSecondSlide = AnimationView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.width * (690 / 750)))
boardAnimationViewForSecondSlide?.animation = Animation.named("Slidetwop1")
slide.addSubview(boardAnimationViewForSecondSlide)
and I define a closure for handle completion play's method
private var animationState: Int = 0 // 0 first slid, 1 second slide
private var changeStateInSlide2: (Bool) -> Void = { finish in
if animationState == 0 {
boardAnimationViewForSecondSlide.animation = Animation.named("Slidetwop2.json")
playSecondPage = true
} else {
boardAnimationViewForSecondSlide.animation = Animation.named("Slidetwop1.json")
playSecondPage = true
}
}
fileprivate var playSecondPage: Bool {
get {
return false
}
set {
if newValue {
boardAnimationViewForSecondSlide.play(completion:changeStateInSlide2)
}
}
}
I think the moste simple is to create a func to launch the animation.
example :
/// Start animation with Lottie
func startAnimation(viewName: AnimationView, jsonName: String) {
viewName.isHidden = false
viewName.animation = Animation.named(jsonName)
viewName.play { (_) in
viewName.isHidden = true
}
After this you can simply call the method one after one :
startAnimation(viewName: checkAnimation, jsonName: "Slidetwop1")
startAnimation(viewName: checkAnimation, jsonName: "Slidetwop2")
Or use the completion handler to call the second.
EDIT: For the loop you can use this solution:
/// Start animation with Lottie
func startAnimation() {
animationLottieView.animation = Animation.named("Slidetwop1")
animationLottieView.play { (finished) in
// completion handler
self.animationLottieView.animation = Animation.named("Slidetwop2")
self.animationLottieView.play { (finishedAnimation) in
self.startAnimation()}
}
}

swift 2 animateWithDuration not repeating

I have been trying to get this animation to work for hours but to no avail. Here is a snapshot. So I have a price label that shows current price of the product, which is in a custom collectionviewcell. When the collectionView:willDisplayCell is called, I then call the below method on my custom collection view cell called animateDiscountPrice.
The animation i am trying to achieve is to add the compare_at price character by character to the end of the current price label. I tried setting the REPEAT option along with repeat count but the animation block is called only once and then the completion block is immediately called. There is no animation basically.
func animateDiscountPrice()
{
let priceText = NSMutableAttributedString(attributedString: self.priceLabel.attributedText!)
let originalPriceText = NSMutableAttributedString(attributedString: self.priceLabel.attributedText!)
let offset = priceText.length
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) {
if let compareAtString : String = self.productData["compare_at_price_min"] as? String {
let compareAtPrice = NSMutableAttributedString(string: "$\(compareAtString)", attributes: myAttribute )
var i = 0
let count = compareAtString.characters.count+1
dispatch_async(dispatch_get_main_queue(), {
UIView.animateWithDuration(NSTimeInterval(count), delay:0, options: [.Repeat, .Autoreverse, .AllowUserInteraction, .CurveLinear],
animations: {
UIView.setAnimationRepeatCount(Float(count))
priceText.appendAttributedString(compareAtPrice.attributedSubstringFromRange(NSMakeRange(i, 1)))
priceText.addAttribute(NSForegroundColorAttributeName, value: discountColor, range: NSMakeRange(offset, i+1))
self.priceLabel.attributedText = priceText
i = i + 1
},
completion: { (finished) in
if(finished)
{
originalPriceText.appendAttributedString(compareAtPrice)
originalPriceText.addAttribute(NSForegroundColorAttributeName, value: discountColor, range: NSMakeRange(offset, compareAtPrice.length))
//self.priceLabel.attributedText = originalPriceText
}
}
)
})
}
}
}
and in the log lines I can see the animation is called only once for each cell being displayed, and calling completion methods afterwards.

For loop in swift seems to randomly choose increment

I have a for loop that executes animations and then removes them on completion, and I am trying to call another method upon completion. Here is my code:
func animateMatch(completion: () -> ()) {
var movingShape = level.shapeAtColumn(pointsContainingShapeArray[0].Column, row: pointsContainingShapeArray[0].Row)
let destinationShape = level.shapeAtColumn(pointsContainingShapeArray[0].Column, row: pointsContainingShapeArray[0].Row)
for everyShape in 1..<pointsContainingShapeArray.count {
movingShape = level.shapeAtColumn(pointsContainingShapeArray[everyShape].Column, row: pointsContainingShapeArray[everyShape].Row)
let Duration: NSTimeInterval = 1
let moveShapes = SKAction.moveTo((destinationShape?.sprite!.position)!,duration: Duration)
moveShapes.timingMode = .EaseOut
movingShape?.sprite?.runAction(moveShapes, completion: {
movingShape?.sprite?.removeFromParent()
print("Removed shape \(everyShape)")
if everyShape == pointsContainingShapeArray.count {
completion()
}
})
}
}
Basically the idea is that every shape in the array after the first position moves to the position of the first one and then removes it from the scene. This works fine, but my completion was getting called at random times every time. So finally I added the print statement in there. Here was the output:
Removed shape 3
Removed shape 1
Removed shape 4
Removed shape 2
At this point I got so frustrated I decided it was time for stack overflow. I can't possibly figure out what's going on here. Thanks for any help!
Here is the code that calls this method:
func handleSwipe(move: Move) {
view.userInteractionEnabled = false
level.performMove(move)
scene.animateMove(move) {
self.view.userInteractionEnabled = true
if hasMatch {
self.view.userInteractionEnabled = false
self.scene.animateMatch() {
self.scene.addNewSpritesForShapes(pointsContainingShapeArray)
hasMatch = false
self.view!.userInteractionEnabled = true
}
}
}
}
The issue isn't the for loop, it's the asynchronous nature of the run action.
When you call moveShapes action, it runs asynchronously before calling the completion back on the original thread. This can happen in any order. You can see this yourself by calling your print synchronously:
for everyShape in 1..<pointsContainingShapeArray.count {
print("Synchronous loop: \(everyShape)")
}
I think you'd be better off using a dispatch_group_t for your final completion:
func animateMatch(completion: () -> ()) {
var movingShape = level.shapeAtColumn(pointsContainingShapeArray[0].Column, row: pointsContainingShapeArray[0].Row)
let destinationShape = level.shapeAtColumn(pointsContainingShapeArray[0].Column, row: pointsContainingShapeArray[0].Row)
// HERE
let group = dispatch_group_create()
dispatch_group_notify(group, dispatch_get_main_queue(), completion)
//
for everyShape in 1..<pointsContainingShapeArray.count {
// HERE
dispatch_group_enter(group)
//
movingShape = level.shapeAtColumn(pointsContainingShapeArray[everyShape].Column, row: pointsContainingShapeArray[everyShape].Row)
let Duration: NSTimeInterval = 1
let moveShapes = SKAction.moveTo((destinationShape?.sprite!.position)!,duration: Duration)
moveShapes.timingMode = .EaseOut
movingShape?.sprite?.runAction(moveShapes, completion: {
movingShape?.sprite?.removeFromParent()
print("Removed shape \(everyShape)")
// HERE
dispatch_group_leave(group)
//
})
}
}

Single SKAction Animation on several nodes using a loop with completion handler

Objective: Apply a single SKAction Animation on several nodes using a loop, while waiting for completion handler.
func animateShuffle(cards: [Card], completionHandler:(success: Bool) -> Void) {
var rotationInRadians:CGFloat = CGFloat(M_PI)
var rotateFirstDeck = SKAction.rotateByAngle(rotationInRadians, duration: 1.0)
var moveFirstDeck = SKAction.moveToX(-150, duration: 1.0)
var returnToOrigPosition = SKAction.moveToX(-125, duration: 1.0)
var firstDeckSequence = SKAction.sequence([moveFirstDeck, rotateFirstDeck, returnToOrigPosition])
var rotateSecondDeck = SKAction.rotateByAngle(-rotationInRadians, duration: 1.0)
var moveSecondDeck = SKAction.moveToX(-100, duration: 1.0)
var secondDeckSequence = SKAction.sequence([moveSecondDeck, rotateSecondDeck, returnToOrigPosition])
for (index, Card) in enumerate(cards){
if index % 2 == 0{
Card.image.runAction(firstDeckSequence)
}
else{
Card.image.runAction(secondDeckSequence)
}
}
//hack
cards[0].image.runAction(firstDeckSequence, completion: { () -> Void in
completionHandler(success: true)
})
}
Here I call the function which kicks off another Animation:
animateShuffle(newDeck.deck, completionHandler: { (success) -> Void in
print("entered")
var drawnCards = [Card]()
if let areThereCards = newDeck.drawCards(4){
drawnCards = areThereCards
}
self.dealCards(drawnCards)
})
I used a hack to get to 99% of where I want to be but my gut tells me there is better way to do this. How can I tell when the last node has finished animating?
Both sequences run for 3 seconds so when the first completion block runs you can safely assume they are all done. To be 100% certain set a bool ivar in the completion handler and then run your post-sequence code in the didEvaluateActions method of the scene.
Alternatively count how many sequences you run, then increase a counter in completion block, and run your code when both counters match.

Multiple swift animations in parallel not working

i have this code animating some elements (total of 3) in a view.
for element in elements{
if element.value != radians {
UIView.animateWithDuration(0.99,
animations: {
element.transform = CGAffineTransformMakeRotation(CGFloat(radians))
}, completion: {
finished in
element.value = radians
})
}
}
When 2 or more elements should be animated (UIView.animateWithDuration is called 2 or more times one after another), only one is animating and the animation is quite choppy. I know that i should write everything in the animation block, but i can't figure out how to do it.
Please help me.
Just put the for loop inside the animation block.
UIView.animateWithDuration(0.99,
animations: {
for element in elements {
if element.value != radians {
element.transform = CGAffineTransformMakeRotation(CGFloat(radians))
}
}
}, completion: { _ in
element.value = radians
})

Resources