我正在研究iOS开发.当我添加一个rect视图并希望它受重力影响,构建并运行我的测试应用程序时,我发现它确实没有引力.
这是我的viewController.m中的viewDidLoad代码:
这是我的viewController.m中的viewDidLoad代码:
[super viewDidLoad]; // Do any additional setup after loading the view,typically from a nib. UIView *squre = [[UIView alloc] initWithFrame:CGRectMake(100,100,100)]; squre.backgroundColor = [UIColor grayColor]; [self.view addSubview:squre]; UIDynamicAnimator *_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view]; UIGravityBehavior *_gravity = [[UIGravityBehavior alloc] initWithItems:@[squre]]; [_animator addBehavior:_gravity];
解决方法
当viewDidLoad返回时,您的UIDynamicAnimator将被释放.如果它被解除分配,它就无法动画.建立一个属性:
@property (nonatomic) UIDynamicAnimator *animator;
并设置它:
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];