#define SCREEN_SIZE [UIScreen mainScreen].bounds.size
#define KImageCount 3
#define KImage_Height 250
@interface ViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView * scrollView;
@property (nonatomic, strong) UIPageControl * pageControl;
@property (nonatomic, strong) NSTimer * timer;
@end
@implementation ViewController
- (UIScrollView *)scrollView{
if (_scrollView == nil) {
_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_SIZE.width, KImage_Height)];
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
}
return _scrollView;
}
- (UIPageControl *)pageControl{
if (_pageControl == nil) {
_pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.scrollView.frame.size.height - 30, SCREEN_SIZE.width, 20)];
_pageControl.currentPageIndicatorTintColor = [UIColor colorWithRed:65 / 255.0 green:168 / 255.0 blue:100/255.0 alpha:1.0];
_pageControl.pageIndicatorTintColor = [UIColor grayColor];
}
return _pageControl;
}
- (void)setView{
[self.view addSubview:self.scrollView];
[self.view addSubview:self.pageControl];
CGFloat imageY = 0;
CGFloat imageW = SCREEN_SIZE.width;
CGFloat imageH = KImage_Height;
for (int i = 0; i < KImageCount; i++) {
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * imageW, imageY, imageW, imageH)];
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg", i+1]];
[self.scrollView addSubview:imageView];
}
self.scrollView.contentSize = CGSizeMake(KImageCount * imageW, 0);
self.scrollView.delegate = self;
self.pageControl.numberOfPages = KImageCount;
[self addTimer];
}
- (void)addTimer {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop]addTimer:self.timer forMode:NSDefaultRunLoopMode];
}
- (void)nextImage{
int i = (int)self.pageControl.currentPage;
if (i == KImageCount - 1) {
i = -1;
}
i++;
[self.scrollView setContentOffset:CGPointMake(i * self.scrollView.frame.size.width, 0) animated:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
[self turnOffTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[self addTimer];
}
- (void)turnOffTimer{
[self.timer invalidate];
self.timer = nil;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
self.pageControl.currentPage = (self.scrollView.frame.size.width * 0.5 + self.scrollView.contentOffset.x) / self.scrollView.frame.size.width;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"轮播图";
[self setView];
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/darongzi1314/article/details/46728411