//
// ViewController.m
// ScrollView循环滚动
//
// Created by Cuikeyi on 15/8/10.
// Copyright (c) 2015年 Cuikeyi. All rights reserved.
//
#import "ViewController.h"
// 加载图片的个数
#define kCount 30
#define kWidth self.view.bounds.size.width
#define kHeight self.view.bounds.size.height
@interface ViewController () <UIScrollViewDelegate>
@property (nonatomic, weak) UIImageView *preImageView;
@property (nonatomic, weak) UIImageView *currentImageView;
@property (nonatomic, weak) UIImageView *nextImageView;
@property (nonatomic, weak) UIScrollView *scrollerView;
//记录当前是第几张
@property(nonatomic,assign) int index;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
scrollView.delegate = self;
scrollView.pagingEnabled = YES;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.contentSize = CGSizeMake(kCount * kWidth, 0);
[self.view addSubview:scrollView];
self.scrollerView = scrollView;
for (int i = 0; i < 3; i++) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * kWidth, 0, kWidth, kHeight)];
if (i == 0) {
self.preImageView = imageView;
} else if (i == 1) {
self.currentImageView = imageView;
} else if (i == 2) {
self.nextImageView = imageView;
}
[self.scrollerView addSubview:imageView];
}
// 设置当前页数为图片的总数,因为循环滚动靠取余判断页数
_index = kCount;
[self settingImage];
}
//图片赋值
-(void)settingImage
{
// UIImage imageWithContentsOfFile:这个方法当图片不用时候可以释放图片, UIImage imageNamed: 方法一旦创建图片后,图片会一直在内存中,直到程序退出才会被释放。(注:一般大图片加载用第一个方法,一直用到的系统图片用第二种方法创建)
self.currentImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d.jpg",_index % kCount] ofType:nil]];
self.nextImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d.jpg",(_index + 1) % kCount] ofType:nil]];
self.preImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d.jpg",(_index - 1) % kCount] ofType:nil]];
// 始终让currentImageView处在中间位置
self.scrollerView.contentOffset = CGPointMake(kWidth, 0);
}
#pragma mark ----
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int page = (int)scrollView.contentOffset.x / kWidth;
if (_index == kCount) {
_index += kCount;
}
if (page == 0) {
_index--;
[self settingImage];
}
if (page == 2) {
_index++;
[self settingImage];
}
}
@end