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

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

#import <UIKit/UIKit.h>
//new
@interface ViewController : UIViewController<UICollisionBehaviorDelegate>
{
    UIDynamicAnimator * _animator;
    UIGravityBehavior * _gravity;
    UICollisionBehavior * _ground;
}
@end

.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView * apple = [[UIView alloc] initWithFrame:CGRectMake(40,40, 40, 40)];
    apple.backgroundColor = [UIColor redColor];
    [self.view addSubview:apple];
    
    _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
    _gravity = [[UIGravityBehavior alloc] initWithItems:@[apple]];
    [_animator addBehavior:_gravity];
    
    _ground = [[UICollisionBehavior alloc] initWithItems:@[apple]];
    _ground.translatesReferenceBoundsIntoBoundary = YES;
    [_animator addBehavior:_ground];
    //new
    _ground.collisionDelegate = self;
}

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

.m   仍在viewController中

- (void)collisionBehavior:(UICollisionBehavior *)behavior beganContactForItem:(id<UIDynamicItem>)item withBoundaryIdentifier:(id<NSCopying>)identifier atPoint:(CGPoint)p{
    NSLog(@"好疼,我撞在%f,%f,%@",p.x,p.y,identifier);
}

小知识补充:

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

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

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

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

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


    [_ground addBoundaryWithIdentifier:@"apple" fromPoint:CGPointMake(10, 10) toPoint:CGPointMake(320, 568)];//通过这个可以设置重力加速度的方向

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



运行一下,看看效果吧。

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

群号:336146073

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





1楼fyn6417前天 09:07
点了半天顶也没反应,我就点了一下踩,哎呦 你猜怎么着
Re: Liar0606前天 09:16
回复fyn6417n我就看见了呗。。