IOS基础之毛毛虫案例-重力
生活随笔
收集整理的這篇文章主要介紹了
IOS基础之毛毛虫案例-重力
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
IOS基礎(chǔ)之毛毛蟲案例-重力
// // ViewController.m // 17-毛毛蟲案例-重力 // // Created by 魯軍 on 2021/4/17. //#import "ViewController.h"@interface ViewController () @property(nonatomic,strong)UIDynamicAnimator *animator; @property(nonatomic,strong)UIAttachmentBehavior *attach; @property(nonatomic,strong)NSMutableArray *bodys; @end@implementation ViewController#pragma mark: 懶加載 //懶加載。只創(chuàng)建一次 就是單例 只創(chuàng)建一次 - (UIDynamicAnimator *)animator{if(!_animator){_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];}return _animator;}- (NSMutableArray *)bodys {if(!_bodys){_bodys = [NSMutableArray array];}return _bodys; }- (void)viewDidLoad {[super viewDidLoad];CGFloat w = 30;CGFloat h = 30;CGFloat y = 100;for(int i=0;i<9;++i){UIView * wormView = [[UIView alloc] init];CGFloat x = i * w;wormView.frame = CGRectMake(x, y, w, h);wormView.backgroundColor = [UIColor redColor];wormView.layer.cornerRadius = w *0.5;wormView.layer.masksToBounds = YES;if(i==8){wormView.frame= CGRectMake(x, y-h*0.5, 2*w, 2*h);wormView.backgroundColor = [UIColor blueColor];wormView.layer.cornerRadius = w;//添加一個(gè)拖拽手勢(shì)UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];//2 對(duì)某個(gè)view 使用這個(gè)手勢(shì)[wormView addGestureRecognizer:pan];}[self.view addSubview:wormView];[self.bodys addObject:wormView];}//附著for(int j=0;j<self.bodys.count-1;++j){UIAttachmentBehavior *attachment = [[UIAttachmentBehavior alloc] initWithItem:self.bodys[j] attachedToItem:self.bodys[j+1]];[self.animator addBehavior:attachment];}UIGravityBehavior * g = [[UIGravityBehavior alloc] initWithItems:self.bodys];[self.animator addBehavior:g];UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:self.bodys];collision.translatesReferenceBoundsIntoBoundary = YES;[self.animator addBehavior:collision]; }-(void)pan:(UIPanGestureRecognizer *)sender{CGPoint p= [sender locationInView:self.view];//創(chuàng)建動(dòng)畫者對(duì)象// 見懶加載//創(chuàng)建附著行為if(!self.attach){UIAttachmentBehavior *attach = [[UIAttachmentBehavior alloc] initWithItem:sender.view attachedToAnchor:p];self.attach = attach;}self.attach.anchorPoint = p;//把行為添加到動(dòng)畫者對(duì)象中[self.animator addBehavior:self.attach];//撒手的時(shí)候if(sender.state == UIGestureRecognizerStateEnded){[self.animator removeBehavior:self.attach];} }@end總結(jié)
以上是生活随笔為你收集整理的IOS基础之毛毛虫案例-重力的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 成大事必备9种能力 9种手段 9种心态(
- 下一篇: 史上最全换档讲解手动档汽车的换挡技巧