您的位置:首页 > 移动开发 > IOS开发

ios ScrollerView之图片轮播器

2015-08-03 15:20 281 查看

ios ScrollerView之图片轮播器

今天项目中用到了图片轮播器,写完之后贴到博客里来记录一下,也方便有兴趣的同学学习

#import "JYHCarouselController.h"

@interface JYHCarouselController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation JYHCarouselController

- (void)viewDidLoad {
[super viewDidLoad];
NSArray *array = @[@"img_01",@"img_02",@"img_03"];
[self imageCarouselWithimageArray:array];
}
- (void) imageCarouselWithimageArray:(NSArray *)imageArray {

//图片的宽度和X值
CGFloat imageW = self.scrollView.frame.size.width;
CGFloat imageH = self.scrollView.frame.size.height;
CGFloat imageY = 0;

//将图片加入到scrollerView中
for(int i = 0; i < imageArray.count; i++) {

UIImageView *imageView = [[UIImageView alloc]init];

//设置imageView的frame
CGFloat imageX = i * imageW;
imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);

//设置显示图片
NSString *imageName = imageArray[i];
imageView.image = [UIImage imageNamed:imageName];

//将图片加入到scrollView中
[self.scrollView addSubview:imageView];
}

//设置内容尺寸
self.scrollView.contentSize = CGSizeMake(imageArray.count * imageW, 0);

//隐藏水平滚动条且分页
self.scrollView.showsHorizontalScrollIndicator = NO;
self.scrollView.pagingEnabled = YES;
self.scrollView.delegate = self;

//页面指示器的总页数
self.pageControl.numberOfPages = imageArray.count;

//添加定时器
[self addTimer];
}

- (void)addTimer{
self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
//将定时器添加到当前的运行循环中(不添加会导致拖动其他控件时图片轮播器会停止)
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

-(void)nextImage {
//增加页面指示器的页码
long page = 0;

if(self.pageControl.currentPage == self.pageControl.numberOfPages - 1) {
page = 0;
} else {
page = self.pageControl.currentPage + 1;
}
//让scrollView滚动到正确位置
CGPoint offset = CGPointMake(page * self.scrollView.frame.size.width, 0);
[self.scrollView setContentOffset:offset animated:YES];
}

//当scrollView滚动时调用
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
// 根据scrollView的滚动位置决定pageControl显示第几页
CGFloat scrollW = scrollView.frame.size.width;
int page = (scrollView.contentOffset.x + scrollW * 0.5) / scrollW;
self.pageControl.currentPage = page;

}

//当scrollView开始拖动时调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
[self removeTimer];
}

//移除定时器
- (void)removeTimer {
[self.timer invalidate];//定时器一旦停止就废了
self.timer = nil;
}

//当scrollView停止拖动时调用
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
[self addTimer];
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: