1. 程式人生 > >ios-UIDynamicAnimator(物理模擬動畫)

ios-UIDynamicAnimator(物理模擬動畫)

實現物理模擬的效果 滑鼠點選處,小球彈到那裡 
#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,weak)IBOutlet UIImageView *iconImageView;
@property(nonatomic,strong)UIDynamicAnimator *animator;

@end

@implementation ViewController

-(UIDynamicAnimator *)animator
{
    if (!_animator) {
        //建立物理模擬器(referecnce 物理模擬範圍)
        self.animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
        
    }
    return _animator;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:touch.view];
    
    UISnapBehavior *snap = [[UISnapBehavior alloc]initWithItem:self.iconImageView snapToPoint:point];
    
    //減震
    snap.damping = 0.5;
    [self.animator removeAllBehaviors];//移除之前所有行為
    [self.animator addBehavior:snap];//新增新的行為
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end