#import "LSViewController.h"
#define ImageCount 5
@interface LSViewController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation LSViewController
- (void)viewDidLoad
{
[super viewDidLoad];
CGFloat width = self.scrollView.frame.size.width;
CGFloat height = self.scrollView.frame.size.height;
//1.scrollView(有两件事)
// 2.图片(代码增加到scrollView)
for (int i = 1; i < ImageCount + 1; i++) {
UIImageView *imageView = [[UIImageView alloc] init];
CGFloat imageX = (i - 1) * width;
CGFloat imageY = 0.f;
imageView.frame = CGRectMake(imageX, imageY, width, height);
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_%02d", i]];
[self.scrollView addSubview:imageView];
}
self.scrollView.contentSize = CGSizeMake(ImageCount * width, 0);
// 拖动分页
self.scrollView.pagingEnabled = YES;
// 设置代理
self.scrollView.delegate = self;
// 设置总页数
self.pageControl.numberOfPages = ImageCount;
[self addScrollTimer];
}
- (void)addScrollTimer
{
// 创建定时器(两种方式:timerWithTimeInterval)
// self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
//
self.timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)removeScrollTimer
{
[self.timer invalidate];
self.timer = nil;
}
// 下一页
- (void)nextPage
{
int currentPage = self.pageControl.currentPage;
currentPage ++;
if (currentPage == 5) {
currentPage = 0;
}
CGFloat width = self.scrollView.frame.size.width;
CGPoint offset = CGPointMake(currentPage * width, 0.f);
// self.scrollView.contentOffset = offset;
// [self.scrollView setContentOffset:offset animated:YES];
[UIView animateWithDuration:.2f animations:^{
self.scrollView.contentOffset = offset;
}];
}
#pragma mark - UIScrollViewDelegate实现方法-
// scrollView滚动时执行
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// NSLog(@"scrollViewDidScroll");
CGPoint offset = self.scrollView.contentOffset;
CGFloat offsetX = offset.x;
CGFloat width = self.scrollView.frame.size.width;
int pageNum = (offsetX + .5f * width) / width;
self.pageControl.currentPage = pageNum;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// NSLog(@"scrollViewWillBeginDragging");
[self removeScrollTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
// NSLog(@"scrollViewDidEndDragging");
[self addScrollTimer];
}
@end