目标:实现通过手势进行图片的切换 通过左扫右扫 来实现(纯代码)
添加三个属性 1uiImageView 用来显示图片的view
2 index 用来表示图片的索引
3 ISLeft 判断是不是向左滑
下边是详细的代码:
- (void)viewDidLoad { [super viewDidLoad]; self.index = 0; self.ISLeft = YES; _imageView = [[UIImageView alloc]initWithFrame:self.view.frame]; // _imageView.backgroundColor = [UIColor redColor]; _imageView.contentMode = UIViewContentModeScaleAspectFit;//合适的大小 self.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.png",_index]]; [self.view addSubview:_imageView]; //用户交互设置 self.imageView.userInteractionEnabled = YES; //添加扫动得手势 UISwipeGestureRecognizer *swipL = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swip:)]; swipL.direction = UISwipeGestureRecognizerDirectionLeft; [self.imageView addGestureRecognizer:swipL]; UISwipeGestureRecognizer *swipR = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swip:)]; swipR.direction = UISwipeGestureRecognizerDirectionRight; [self.imageView addGestureRecognizer:swipR]; }
设置转场动画 :在手势里边进行实现
手势的实现以及转场动画:
-(void)swip:(UISwipeGestureRecognizer *)sender { if(sender.direction == UISwipeGestureRecognizerDirectionLeft) { if(self.index>=0) { if(self.index>0) { self.index--; } else { self.index =3; } self.ISLeft = YES; } } else { self.ISLeft = NO; if(self.index<3) { self.index++; if(self.index ==3) { self.index =0; } } } //转场动画 CATransition *trans = [[CATransition alloc]init]; //转场动画的类型 trans.type =@"push"; //判断是不是向左滑 if(self.ISLeft) { trans.subtype = kCATransitionFromTop; } else { trans.subtype = kCATransitionFromBottom; } trans.duration = 0.5f; [self.imageView.layer addAnimation:trans forKey:@"trans"]; //切换图画 self.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld",_index]]; }