//如果定时器已开启,先停止再重新开启
if (self.timer) [self stopTimer]; self.timer = [NSTimer timerWithTimeInterval:self.time target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)nextPage { //动画改变scrollview的偏移量就可以实现自动滚动
[self.scrollView setContentOffset:CGPointMake(self.width * 2, 0) animated:YES];
}
注意:setContentOffset:animated:方法执行完毕后不会调用scrollview的scrollViewDidEndDecelerating方法,但是会调用scrollViewDidEndScrollingAnimation方法,因此我们要在该方法中调用pauseScroll
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
[self pauseScroll];
}
拖拽时停止自动滚动
当我们手动拖拽图片时,需要停止自动滚动,此时我们只需要让定时器失效就行了,当停止拖拽时,重新启动定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[self.timer invalidate];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[self startTimer];
}
加载图片
实际开发中,我们很少会轮播本地图片,大部分都是服务器获取的,也有可能既有本地图片,也有网络图片,那要如何来加载呢?
定义4个属性
-
NSArray imageArray:暴露在.h文件中,外界将要加载的图片或路径数组赋值给该属性
-
NSMutableArray images:用来存放图片的数组
-
NSMutableDictionary imageDic:用来缓存图片的字典,key为URL
-
NSMutableDictionary operationDic:用来保存下载操作的字典,key为URL
-
判断外界传入的是图片还是路径,如果是图片,直接加入图片数组中,如果是路径,先添加一个占位图片,然后根据路径去下载图片
_images = [NSMutableArray array];for (int i = 0; i < imageArray.count; i++) { if ([imageArray[i] isKindOfClass:[UIImage class]]) {
[_images addObject:imageArray[i]];//如果是图片,直接添加到images中
} else if ([imageArray[i] isKindOfClass:[NSString class]]){
[_images addObject:[UIImage imageNamed:@"placeholder"]];//如果是路径,添加一个占位图片到images中
[self downloadImages:i]; //下载网络图片
}
}
下载图片,先从缓存中取,如果有,则替换之前的占位图片,如果没有,去沙盒中取,如果有,替换占位图片,并添加到缓存中,如果没有,开启异步线程下载
- (void)downloadImages:(int)index { NSString *key = _imageArray[index]; //从字典缓存中取图片
UIImage *image = [self.imageDic objectForKey:key]; if (image) {
_images[index] = image;//如果图片存在,则直接替换之前的占位图片
}else{ //字典中没有从沙盒中取图片
NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *path = [cache stringByAppendingPathComponent:[key lastPathComponent]]; NSData *data = [NSData dataWithContentsOfFile:path]; if (data) { //沙盒中有,替换占位图片,并加入字典缓存中
image = [UIImage imageWithData:data];
_images[index] = image;
[self.imageDic setObject:image forKey:key];
}else{ //字典沙盒都没有,下载图片
NSBlockOperation *download = [self.operationDic objectForKey:key];//查看下载操作是否存在
if (!download) {//不存在
//创建一个队列,默认为并发队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //创建一个下载操作
download = [NSBlockOperation blockOperationWithBlock:^{ NS