iOS7 UIKit动力学-碰撞特性UICollisionBehavior 下

上文讲到了为window加一个边界,实现碰撞的效果,接下来我们将提到一个委托方法:

- (void)collisionBehavior:(UICollisionBehavior *)behavior 

beganContactForItem:(id<UIDynamicItem>)item 

withBoundaryIdentifier:(id<NSCopying>)identifier a

tPoint:(CGPoint)p;

这个方法是在边界发生碰撞的时候才去执行的

UICollisionBehavior 这个和tableview的委托方法一样理解,item是碰撞的对象,identifier为对象添加定义,p为发生碰撞的位置。

如何实现碰撞这个方法呢,如下:

引用<UICollisionBehaviorDelegate>这个委托,然后把_ground对象的委托给当前这个viewController。方法如下:

.h

  1. #import <UIKit/UIKit.h>  
  2. //new  
  3. @interface ViewController : UIViewController<UICollisionBehaviorDelegate>  
  4. {  
  5.     UIDynamicAnimator * _animator;  
  6.     UIGravityBehavior * _gravity;  
  7.     UICollisionBehavior * _ground;  
  8. }  
  9. @end  

.m

  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     UIView * apple = [[UIView alloc] initWithFrame:CGRectMake(40,404040)];  
  5.     apple.backgroundColor = [UIColor redColor];  
  6.     [self.view addSubview:apple];  
  7.       
  8.     _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];  
  9.     _gravity = [[UIGravityBehavior alloc] initWithItems:@[apple]];  
  10.     [_animator addBehavior:_gravity];  
  11.       
  12.     _ground = [[UICollisionBehavior alloc] initWithItems:@[apple]];  
  13.     _ground.translatesReferenceBoundsIntoBoundary = YES;  
  14.     [_animator addBehavior:_ground];  
  15.     //new  
  16.     _ground.collisionDelegate = self;  
  17. }  

设置_ground.collisionDelegate为试图控制器,之后当界面在发生碰撞,就可以调用一开始所说的委托方法了。

.m   仍在viewController中

  1. <span style="font-size:14px;">- (void)collisionBehavior:(UICollisionBehavior *)behavior beganContactForItem:(id<UIDynamicItem>)item withBoundaryIdentifier:(id<NSCopying>)identifier atPoint:(CGPoint)p{  
  2.     NSLog(@"好疼,我撞在%f,%f,%@",p.x,p.y,identifier);  
  3. }</span>  

小知识补充:

UICollisionBehavior的属性中有一个叫做action的属性

@property (nonatomic,copy)void (^action)(void);

很明显的能看出来,这是一个block的结构,无参数,无返回值。

  1. _ground.action = ^{  
  2.     NSLog(@"%@, %@",  
  3.           NSStringFromCGAffineTransform(apple.transform), NSStringFromCGPoint(apple.center));  
  4. };  

你可以通过这个Block来获得某个有动力学属性的对象的各种运行效果,在这里你可以看到动态引擎使用的组合变换和帧偏移位置视图根据基本的物理模型。而动态的确切值适用于这些属性可能是不感兴趣,重要的是要知道他们被应用。因此,如果您以编程方式更改帧或改变对象的属性,你可以预期,这些值将被覆盖。这意味着您不能使用转换扩展对象虽然是动态的控制下。动态行为使用术语的方法签名的物品而不是视图。


  1. [_ground addBoundaryWithIdentifier:@"apple" fromPoint:CGPointMake(1010) toPoint:CGPointMake(320568)];//通过这个可以设置重力加速度的方向  

通过这个方法,你可以设置视图运动的起始位置和终点位置,这里的@"apple"可以在委托方法中,被提取出来的。



运行一下,看看效果吧。

点击关注我,更多精彩内容!!!

群号:336146073

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值