无限轮播图的实现方法有很多种,但大多是借助collectionView或者是scrollView+imageView去实现。最近在研究动画,就试着用一个imageView+CATransition动画写了一个,效果图如下:
RunLoopView.gif整体思路:
给imageView添加左右滑动手势并给imageView图层添加CATransition(类型为kCATransitionPush)动画。在手势响应事件里通过判断滑动手势的方向,给CATransition实例对象设置相应得子类型(kCATransitionFromLeft/kCATransitionFromRight)。
核心代码:
#pragma mark -- Tap Action
- (void)changeDisplayImage:(UISwipeGestureRecognizer *)sender
{
[self removeTimer];
if (sender.direction == UISwipeGestureRecognizerDirectionLeft) {
self.index ++;
if (self.index == self.images.count) {
self.index = 0;
}
self.transition.subtype = kCATransitionFromRight;
}else if (sender.direction == UISwipeGestureRecognizerDirectionRight) {
self.index --;
if (self.index < 0) {
self.index = self.images.count - 1;
}
self.transition.subtype = kCATransitionFromLeft;
}
[self loadData];
}
// 添加定时器
- (void)addTimer
{
_timer = [NSTimer scheduledTimerWithTimeInterval:3.f target:self selector:@selector(automaticChangeImage) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
// 移除定时器
- (void)removeTimer
{
if (_timer) {
[_timer invalidate];
_timer = nil;
}
}
// 自动轮播图片
- (void)automaticChangeImage
{
self.index ++;
if (self.index == self.images.count) {
self.index = 0;
}
self.transition.subtype = kCATransitionFromRight;
[self loadData];
}
// 加载图片和描述
- (void)loadData
{
self.pageControl.currentPage = self.index;
self.imageView.image = self.images[self.index];
self.titleLabel.text = self.titles[self.index];
[self.imageView.layer addAnimation:self.transition forKey:@"transition"];
if (!_timer) {
[self addTimer];
}
}
优缺点分析:
优点:较轻量级,实现以及使用起来都非常简单;
缺点:因为添加的是滑动手势,所以拖拽起来没有反弹的效果(其实这个仁者见仁智者见智啦,个人觉得这种效果很省力气,体验蛮好的)。
Demo地址:
“予人玫瑰,手有余香”