iOS:UIView的block函数实现转场动画---单视图

使用UIView动画函数实现转场动画——单视图
+ (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;
 
参数说明:
–duration:动画的持续时间
–view:需要进行转场动画的视图
–options:转场动画的类型
–animations:将改变视图属性的代码放在这个block中
–completion:动画结束后,会自动调用这个block
 
 

具体实例如下:

实现功能:还是往工程中导入5张图片素材,创建图像视图控件,然后通过向左或向右扫动手势实现图像视图中图片的轮换,即实现转场动画。

代码如下:

//导入图片素材

//声明属性

#import "ViewController.h"

@interface ViewController ()
@property (strong,nonatomic)UIImageView *imageView;//图像视图
@property (assign,nonatomic)NSInteger index;       //当前图片的索引
@end

//初始化,创建图像视图控件并设置图片,同时创建扫动手势,添加扫动事件

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置当前图片为第一张
    self.index = 1;
    
    //初始化图像视图
    self.imageView = [[UIImageView alloc]initWithFrame:self.view.frame];
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"s%ld.jpg",self.index]]];
    
    
    //允许图像视图进行用户交互
    self.imageView.userInteractionEnabled = YES;
    [self.view addSubview:self.imageView];
    
    
    
    //创建扫动手势
    UISwipeGestureRecognizer *leftswipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipe:)];
    //设置扫动方向为向左扫
    leftswipe.direction = UISwipeGestureRecognizerDirectionLeft;
    //添加扫动手势
    [self.imageView addGestureRecognizer:leftswipe];
    
    //创建扫动手势
    UISwipeGestureRecognizer *rightswipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipe:)];
    //设置扫动方向为向右扫
    rightswipe.direction = UISwipeGestureRecognizerDirectionRight;
    //添加扫动手势
    [self.imageView addGestureRecognizer:rightswipe];
}

//处理扫动手势事件,进行转场动画的创建并执行动画

 

#pragma mark -扫动手势
-(void)swipe:(UISwipeGestureRecognizer *)sender
{
    //根据手势的方向改变图片的索引,一共5张图片
    if (sender.direction == UISwipeGestureRecognizerDirectionLeft)//向左扫
    {
        if (self.index >1 )
        {
            self.index--;
        }
        else
        {
            self.index = 5;
        }
    }
    else //向右扫
    {
        if (self.index <5)
        {
            self.index++;
        }
        else
        {
            self.index = 1;
        }
    }
    //使用block函数添加UIView单视图转场动画
    [UIView animateWithDuration:1.0f animations:^{
       [self.imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"s%ld.jpg",self.index]]];
    } completion:nil];
}

 

演示结果如下:

 没扫动手势一次,图片就轮换一次,即转场显示的图片依次为:

 

 

posted @ 2015-10-16 23:09  XYQ全哥  阅读(513)  评论(0编辑  收藏  举报