改几个小地方就可以直接使用了。
#define kImageCount 2
@interface ScrollViewController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (nonatomic, weak) NSTimer *timer;
@end
@implementation ScrollViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self pLScroLLview];
}
- (void)pLScroLLview
{
// 1.添加图片(frame-改)
CGFloat imageW = self.view.bounds.size.width;
CGFloat imageH = 130;
CGFloat imageY = 0;
for (int index = 0; index <= kImageCount; index++) {
CGFloat imageX = index * imageW;
UIImageView *imageView = [[UIImageView alloc] init];
imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_%02d", index+1]];//(改)
[self.scrollView addSubview:imageView];
}
// 2.设置内容区域
self.scrollView.contentSize = CGSizeMake(kImageCount * self.scrollView.bounds.size.width, 0);
// 3.设置分页控件起始页数
self.pageControl.currentPage = 0;
// 4.添加时钟
[self startTimer];
}
- (void)startTimer
{
self.timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}
- (void)updateTimer
{
self.pageControl.currentPage = (self.pageControl.currentPage + 1) % kImageCount;
[self pageChanged:self.pageControl];
}
#pragma mark - 分页控件监听方法
- (void)pageChanged:(UIPageControl *)page
{
CGFloat x = page.currentPage * self.scrollView.bounds.size.width;
[self.scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
}
#pragma mark - 滚动视图代理方法
/** 滚动停止 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
// 根据contentOffset计算页数
int page = scrollView.contentOffset.x / scrollView.bounds.size.width;
self.pageControl.currentPage = page;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (self.timer) return;
self.pageControl.currentPage = (scrollView.contentOffset.x + scrollView.frame.size.width * 0.5) / scrollView.frame.size.width;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self.timer invalidate];
self.timer = nil;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[self startTimer];
}
@end
网友评论