Search code examples
iosiphoneuiviewuidynamicbehavioruikit-dynamics

iOS adding UIGravityBehavior to subviews does not always work


I'm adding UIGravityBehavior programmatically to subviews with but not always work. I have 4 views in main view with tags 101,102,103,104 as it shows in the image:

enter image description here

but it seems like only works on view with tag 103 and 104 for some reason. Here is my code:

-(void)viewsGoinDown
{
    NSPredicate *tagPredicate = [NSPredicate predicateWithFormat:@"self.tag >= 100"];
    NSArray *resultArray = [[self.view subviews] filteredArrayUsingPredicate:tagPredicate];
    for (NSUInteger i =0 ; i < resultArray.count; i++)
    {
        NSUInteger sleeping = 2;
        UIView *mySubview = resultArray [i];
        if (i == 0)
        {
            sleeping = 0;

        }

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            sleep(sleeping);


            dispatch_async(dispatch_get_main_queue(), ^()
                           {
                               [self moveDownViews:mySubview];

                           });


        });
    }
}

-(void)moveDownViews:(UIView*)myView
{
    self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
    self.gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[myView]];
    self.gravityBehavior.magnitude = 1;
    [self.animator addBehavior:self.gravityBehavior];

}

My question is why only works for those 2 subviews?, What I'm doing wrong?

I'll really appreciate your help


Solution

  • Please find the working code below:

    P.S. I have taken the liberty to change some of the implementation which you can change back according to your taste.

    -(void)viewsGoinDown
    {
        NSPredicate *tagPredicate = [NSPredicate predicateWithFormat:@"self.tag >= 100"];
        NSArray *resultArray = [[self.view subviews] filteredArrayUsingPredicate:tagPredicate];
        NSUInteger sleeping = 0;
        for (NSUInteger i =0 ; i < resultArray.count; i++)
        {
    
            UIView *mySubview = resultArray [i];
            [self performSelector:@selector(moveDownViews:) withObject:mySubview afterDelay:sleeping];
            sleeping++;
        }
    
    }
    
    -(void)moveDownViews:(UIView *)myView
    {
        self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
        self.gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[myView]];
        self.gravityBehavior.magnitude = 1;
        [self.animator addBehavior:self.gravityBehavior];
    }