UIGravityBehavior无效

mar*_*hah 5 objective-c ios7 uidynamicbehavior

我正在努力学习UIKit Dynamics.
我创建了一个盒子视图并在其上添加了UIGravityBehavior,但是当我运行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
Run Code Online (Sandbox Code Playgroud)

这是我的视图controller.m文件.
程序有什么问题?

zee*_*jan 8

如果要在ViewDidLoad中使用它,则需要将UIDynamicAnimator和UIGravityBehavior声明为当前VC的属性.ViewDidLoad完成后,自动引用计数将释放这些对象.

问候


Gre*_*reg 0

你能尝试一下它对我有用吗:

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];
Run Code Online (Sandbox Code Playgroud)

//扩展

尝试在 .m 文件中创建实例变量:

UIDynamicAnimator* _animator;
UIGravityBehavior* _gravity;
Run Code Online (Sandbox Code Playgroud)

在 viewDidLoad 中创建您的框视图,然后添加:

_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
_gravity = [[UIGravityBehavior alloc] initWithItems:@[box]];
[_animator addBehavior:_gravity
Run Code Online (Sandbox Code Playgroud)

它应该可以解决你的问题。