UIGravityBehavior isn't working

1.1k views Asked by At

I'm trying to learn UIKit Dynamics.
I have created a box view and added the UIGravityBehavior on it, but nothing happens when I run the Project!

Viewcontroller.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView* box = [[UIView alloc]initWithFrame:CGRectMake(100, 50, 100, 100)];
    box.backgroundColor = [UIColor blackColor];
    [self.view addSubview:box];
    UIGravityBehavior* gravityBehaviour = [[UIGravityBehavior alloc]init];
    [gravityBehaviour addItem:box];
    UIDynamicAnimator* myAnimator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
    [myAnimator addBehavior:gravityBehaviour];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

This is my view controller.m file.
What is wrong in the program?

4

There are 4 answers

2
Greg On

Can you try that it works for me:

UIView* box = [[UIView alloc]initWithFrame:CGRectMake(100, 50, 100, 100)];
box.backgroundColor = [UIColor blackColor];
[self.view addSubview:box];

UIDynamicAnimator* myAnimator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
UIGravityBehavior* gravityBehaviour = [[UIGravityBehavior alloc] initWithItems:@[box]];
[myAnimator addBehavior: gravityBehaviour];

//EXTENDED

Try create instance variable in your .m file:

UIDynamicAnimator* _animator;
UIGravityBehavior* _gravity;

And in viewDidLoad create your box view and after that add:

_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
_gravity = [[UIGravityBehavior alloc] initWithItems:@[box]];
[_animator addBehavior:_gravity

It should sort your problem.

0
Soyoes On

I think you have to declare your UIDynamicAnimator instance as a Strong type.

For instance, you can define a UIDynamicAnimator as a member of your UIViewController.

@interface ViewController ()
    @property (nonatomic, strong) UIDynamicAnimator *animator;
@end

then in your viewDidLoad

// ... code to init your self.animator and add behaviors
self.animator = animator;
0
zeejan On

If you want to use it in ViewDidLoad, you need to announce UIDynamicAnimator and UIGravityBehavior as properties of the current VC. The Automatic Reference Counting will deallocate those objects after ViewDidLoad finishing.

Regards

0
DannyBios On

There is a very basic tutorial about creating an app using UIGravityBehavior here: https://www.youtube.com/watch?v=vKqjKcVUYPc - Hope it helps.