原创作者:codingZero
导语
在不少项目中,都会有图片轮播这个功能,现在网上关于图片轮播的框架层出不穷,千奇百怪,笔者根据自己的思路,用两个imageView也实现了图片轮播,这里说说笔者的主要思路以及大概步骤,具体代码请看这里,如果觉得好用,请献上你的star。
该轮播框架的优势:
文件少,代码简洁
不依赖任何其他第三方库,耦合度低
同时支持本地图片及网络图片
可修改分页控件位置,显示或隐藏
自定义分页控件的图片,就是这么个性
自带图片缓存,一次加载,永久使用
性能好,占用内存少,轮播流畅
实际使用
我们先看demo,代码如下
运行效果
轮播实现步骤
接下来,笔者将从各方面逐一分析。
层级结构
最底层是一个UIView,上面有一个UIScrollView以及UIPageControl,scrollView上有两个UIImageView,imageView宽高 = scrollview宽高 = view宽高
轮播原理
假设轮播控件的宽度为x高度为y,我们设置scrollview的contentSize.width为3x,并让scrollview的水平偏移量为x,既显示最中间内容
scrollView.contentSize = CGSizeMake(3x, y);
scrollView.contentOffset = CGPointMake(x, 0);
将imageView添加到scrollview内容视图的中间位置
接下来使用代理方法scrollViewDidScroll来监听scrollview的滚动,定义一个枚举变量来记录滚动的方向
typedef enum{
DirecNone,
DirecLeft,
DirecRight
} Direction;@property (nonatomic, assign) Direction direction;
- (void)scrollViewDidScroll:(UIScrollView *)scrollView { self.direction = scrollView.contentOffset.x >x? DirecLeft : DirecRight;
}
使用KVO来监听direction属性值的改变
[self addObserver:self forKeyPath:@"direction" options:NSKeyValueObservingOptionNew context:nil];
判断滚动的方向,当偏移量大于x,表示左移,则将otherImageView加在右边,偏移量小于x,表示右移,则将otherImageView加在左边
- (void)observeva lueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { //self.currIndex表示当前显示图片的索引,self.nextIndex表示将要显示图片的索引
//_images为图片数组
if(change[NSKeyValueChangeNewKey] == change[NSKeyValueChangeOldKey]) return;
if ([change[NSKeyValueChangeNewKey] intValue] == DirecRight) { self.otherImageView.frame = CGRectMake(0, 0, self.width, self.height);
self.nextIndex = self.currIndex - 1;
if (self.nextIndex < 0) self.nextIndex = _images.count – 1;
} else if ([change[NSKeyValueChangeNewKey] intValue] == DirecLeft){ self.otherImageView.frame = CGRectMake(CGRectGetMaxX(_currImageView.frame), 0, self.width, self.height);
self.nextIndex = (self.currIndex + 1) % _images.count;
}
self.otherImageView.image = self.images[self.nextIndex];
}
通过代理方法scrollViewDidEndDecelerating来监听滚动结束,结束后,会变成以下两种情况:
此时,scrollview的偏移量为0或者2x,我们通过代码再次将scrollview的偏移量设置为x,并将currImageView的图片修改为otherImageView的图片
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
[self pauseScroll];
}
- (void)pauseScroll { self.direction = DirecNone;//清空滚动方向
//判断最终是滚到了右边还是左边
int index = self.scrollView.contentOffset.x / x; if (index == 1) return; //等于1表示最后没有滚动,返回不做任何操作
self.currIndex = self.nextIndex;//当前图片索引改变
self.pageControl.currentPage = self.currIndex; self.currImageView.frame = CGRectMake(x, 0, x, y); self.currImageView.image = self.otherImageView.image; self.scrollView.contentOffset = CGPointMake(x, 0);
}
那么我们看到的还是currImageView,只不过展示的是下一张图片,如图,又变成了最初的效果
自动滚动
轮播的功能实现了,接下来添加定时器让它自动滚动,相当简单
- (void)startTimer { //如果只有一张图片,则直接返回,不开启定时器
if (_images.count <= 1) return;