天天看點

輕掃手勢

#import "ViewController.h"

@interface ViewController ()
{
    int _index;
}

@property (nonatomic, weak)UIImageView *imageView;

@end

@implementation ViewController

- (UIImageView *)imageView
{
    if (!_imageView)
    {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1"]];
        imageView.frame = CGRectMake(0, 0, self.view.frame.size.width, 400);
        imageView.userInteractionEnabled = YES;
        [self.view addSubview:imageView];
        
        _imageView = imageView;
    }
    
    return _imageView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    _index = 1;
    
    [self addSwipeGestureToImageView];
}

/**
 *  添加輕掃手勢
 */
- (void)addSwipeGestureToImageView
{
    //注意:支援幾個方向的掃動,就建立一個手勢對象
    //從左向右
    UISwipeGestureRecognizer *leftSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeHandle:)];
    //預設從左向右
    leftSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
    [self.imageView addGestureRecognizer:leftSwipeGesture];
    
    從右向左
    UISwipeGestureRecognizer *rightSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeHandle:)];
    rightSwipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.imageView addGestureRecognizer:rightSwipeGesture];
    
}

- (void)swipeHandle:(UISwipeGestureRecognizer *)gesture
{
    //子類型
    NSString *subType = nil;
    
    //從左向右
    if (gesture.direction == UISwipeGestureRecognizerDirectionRight)
    {
        _index--;
        if (_index == 0) {
            _index = 8;
        }
        subType = kCATransitionFromLeft;
    }
    //從右向左
    else
    {
        _index++;
        if (_index > 8) {
            _index = 1;
        }
        subType = kCATransitionFromRight;
    }
    
    /*
     CATransition 轉場動畫
     CAKeyframeAnimation 關鍵幀動畫
     CABasicAnimation 隐式動畫(基本動畫)
     CAAnimationGroup 動畫組
     */
    
    
    //轉場動畫
    CATransition *transition = [CATransition animation];
    //類型(确定動畫類型)
    transition.type = @"cube";
    //子類型(确定方向)
    transition.subtype = subType;
    //動畫時間
    transition.duration = 1;
    [self.imageView.layer addAnimation:transition forKey:nil];
    
    //修改圖檔
    self.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",_index]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end