Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8961569
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T15:55:27+00:00 2026-06-15T15:55:27+00:00

I am creating an app that will show how a bubble sort works. The

  • 0

I am creating an app that will show how a bubble sort works. The one problem I am having is the animation. It seems to be skipping and the animation is firing all at once. Within my if statement I want to swap the two images and animate the swap. Then I want a delay so once they swap it will go back through the loop and swap the next two images. Below is my code. I have tried many things like sleep() but it did not seems to work. The images are four boxes and I’m swapping them by left to right, smallest to largest.

for (int i = 0; i < 3; i++)
{
    UIImageView *temp1 =   [imagesArray objectAtIndex:i];
    UIImageView *temp2 =  [imagesArray objectAtIndex:i+1];
    temp1Width = temp1.frame.size.width;
    temp2Width = temp2.frame.size.width;
    if (temp1Width > temp2Width)
    {
        CGPoint tempPoint = temp1.center;

        [UIView animateWithDuration:1.0
                              delay: 1.0
                            options: nil
                         animations:^{
                            temp1.center = temp2.center;

                         }
                         completion:^(BOOL finished){
                             [UIView animateWithDuration:1.0
                                                   delay: 0.0
                                                 options: nil
                                              animations:^{
                                                  temp2.center = tempPoint;
                                              }
                                              completion:^(BOOL finished){
                                              }];
                         }];
        [imagesArray exchangeObjectAtIndex:i+1 withObjectAtIndex:i];
    }
}

Any Help would be appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T15:55:28+00:00Added an answer on June 15, 2026 at 3:55 pm

    If you apply an animation to a view that’s already being animated, the new animation replaces the existing animation. It doesn’t just get tacked on to the end. That’s why your version doesn’t work the way you want.

    This happens even if you set a delay on the new animation. The existing animation will be removed, and the new animation will start after the specified delay. This prevents k20’s simple answer from working. (Too bad, because that would be a really easy solution.)

    So, a very simple alternative is to defer adding each additional animation at all. This is pretty easy with the dispatch_after function. First, let’s factor out the code that swaps the views’ Y origins into a helper function:

    static void swapViewYOrigins(UIView *a, UIView *b) {
        CGRect aFrame = a.frame;
        CGRect bFrame = b.frame;
        CGFloat t = aFrame.origin.y;
        aFrame.origin.y = bFrame.origin.y;
        bFrame.origin.y = t;
        a.frame = aFrame;
        b.frame = bFrame;
    }
    

    Now we can write the sort function, making it use dispatch_after to postpone each successive animation:

    - (IBAction)sortButtonWasTapped {
        NSTimeInterval duration = 1;
        dispatch_time_t time = DISPATCH_TIME_NOW;
        for (int i = imagesArray.count - 1; i > 0; --i) {
            for (int j = 0; j < i; ++j) {
                UIView *a = imagesArray[j];
                UIView *b = imagesArray[j+1];
                if (a.frame.size.width > b.frame.size.width) {
                    imagesArray[j] = b;
                    imagesArray[j+1] = a;
                    dispatch_after(time, dispatch_get_main_queue(), ^{
                        [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                            swapViewYOrigins(a, b);
                        } completion:nil];
                    });
                    time = dispatch_time(time, duration * NSEC_PER_SEC);
                }
            }
        }
    }
    

    So this is an ok solution, but it does have one shortcoming. It’s not easy to add a button that cancels the animations, because there’s no API that removes a pending dispatch_after block from the queue.

    If you want to support cancelation, it’s better to explicitly manage the queue of pending operations. We can do that by adding an instance variable to hold the queue:

    @implementation ViewController {
        IBOutletCollection(UIView) NSMutableArray *imagesArray;
        NSMutableArray *pendingSwaps;
    }
    

    Then, we modify sortButtonWasTapped to add a block to the queue instead of calling dispatch_after, and we make it start running the queue after it finishes sorting:

    - (IBAction)sortButtonWasTapped {
        pendingSwaps = [NSMutableArray array];
        for (int i = imagesArray.count - 1; i > 0; --i) {
            for (int j = 0; j < i; ++j) {
                UIView *a = imagesArray[j];
                UIView *b = imagesArray[j+1];
                if (a.frame.size.width > b.frame.size.width) {
                    imagesArray[j] = b;
                    imagesArray[j+1] = a;
                    [pendingSwaps addObject:^{
                        swapViewYOrigins(a, b);
                    }];
                }
            }
        }
    
        [self runPendingSwaps];
    }
    

    We’re using the same swapViewYOrigins function as before. We run the pending swaps like this:

    - (void)runPendingSwaps {
        if (pendingSwaps.count == 0)
            return;
    
        void (^swapBlock)(void) = pendingSwaps[0];
        [pendingSwaps removeObjectAtIndex:0];
        [UIView animateWithDuration:1 animations:swapBlock completion:^(BOOL finished) {
            [self runPendingSwaps];
        }];
    }
    

    So, we just stop if the queue is empty. Otherwise, we take the first block off the queue, and we use it as the animation block of a UIView animation. We give the animation a completion block that calls runPendingSwaps again, which starts the next pending animation (if there is one) after the current one finishes.

    To cancel, we can just set pendingSwaps to nil:

    - (IBAction)cancelButtonWasTapped {
        pendingSwaps = nil;
    }
    

    Note that if the user taps Cancel, the views will not necessarily be in the same order on the screen as they are in imagesArray, because imagesArray is fully sorted when sortButtonWasTapped returns. We can fix that by sorting imagesArray by Y origins (using the built-in sort) before starting the bubble sort:

    - (IBAction)sortButtonWasTapped {
        [self sortImagesArrayByY];
        // etc. same as previous version
    }
    
    - (void)sortImagesArrayByY {
        [imagesArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            CGFloat d = [obj1 frame].origin.y - [obj2 frame].origin.y;
            return
            d < 0 ? NSOrderedAscending
            : d > 0 ? NSOrderedDescending
            : NSOrderedSame;
        }];
    }
    

    With this in place, you can click the Sort button, then click Cancel before the views have been fully sorted on screen, then click Sort again and it will resume (by performing bubble sort again).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a UITableView for an app I am creating that will show Movie
I am creating an app that will point a simple arrow in the direction
I'm creating and app that will rely on a database, and I have all
I'm creating an iPhone app that will have a preloaded set of locations with
I am creating an exercise app that will record the weight used and the
I am working on creating a web app that will query event logs on
I am creating an winform application that will run on a tablet PC. One
I'm creating a layout for an iPad app that will consist of xx number
I am creating a Monotouch iPhone app that will display streaming videos. I have
I'm creating an iPhone app that will pull data down from a Web API,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.