標籤:
目標:實現通過手勢進行圖片的切換 通過左掃右掃 來實現(純程式碼)
添加三個屬性 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 [email protected]"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]]; }
ios手勢複習值之換圖片-轉場動畫(純程式碼)