好的,所以我开始学习 UIDynamics 并想在小盒子上解决它。
我在 ViewController.m 中声明了 UIGravityBehaviour 和 UIDynamicsBehaviour 并对 UIView 进行了编码,但是当我执行代码时,它不起作用。
但正如我在我的 .h 文件中将它们声明为 @property 一样,程序运行得非常好。
这背后的原因是什么?
将其声明为@property 和不将其声明为@property 有什么区别?
这是我的文件。
使用@property 之前
视图控制器.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
视图控制器.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];
UIDynamicAnimator* myAnimator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
UIGravityBehavior* gravityBehaviour = [[UIGravityBehavior alloc] initWithItems:@[box]];
[myAnimator addBehavior: gravityBehaviour];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
在将其声明为@property 之后
视图控制器.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong,nonatomic) UIDynamicAnimator* myAnimator ;
@property (strong,nonatomic) UIGravityBehavior *gravityBehavior;
@property (strong,nonatomic) UICollisionBehavior *collisionBehavior ;
@end
视图控制器.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];
self.myAnimator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
self.gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[box]];
self.collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[box]];
self.collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
[self.myAnimator addBehavior:self.gravityBehavior];
[self.myAnimator addBehavior:self.collisionBehavior];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end