我正在尝试学习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
这是我的视图controller.m文件。
程序有什么问题?
答案 0 :(得分:8)
如果要在ViewDidLoad中使用它,则需要将UIDynamicAnimator和UIGravityBehavior声明为当前VC的属性。自动引用计数将在ViewDidLoad完成后释放这些对象。
此致
答案 1 :(得分: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];
// EXTENDED
在.m文件中尝试创建实例变量:
UIDynamicAnimator* _animator;
UIGravityBehavior* _gravity;
在viewDidLoad中创建您的框视图,然后添加:
_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
_gravity = [[UIGravityBehavior alloc] initWithItems:@[box]];
[_animator addBehavior:_gravity
它应该排序你的问题。
答案 2 :(得分:0)
有一个关于使用UIGravityBehavior在这里创建应用程序的非常基本的教程:https://www.youtube.com/watch?v=vKqjKcVUYPc - 希望它有所帮助。
答案 3 :(得分:0)
我认为您必须将UIDynamicAnimator实例声明为Strong类型。
例如,您可以将UIDynamicAnimator定义为UIViewController的成员。
@interface ViewController ()
@property (nonatomic, strong) UIDynamicAnimator *animator;
@end
然后在你的viewDidLoad
中// ... code to init your self.animator and add behaviors
self.animator = animator;