//封装UIScrollView 方法
- (void)initscroll{
//初始化
self.scrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.view.bounds), 220)];
//self.scrollview.backgroundColor = [UIColor redColor];
//添加到视图
[self.view addSubview:self.scrollview];
//设置滚动视图的长度
[self.scrollview setContentSize:CGSizeMake(CGRectGetWidth(self.view.bounds)*4, 0)];
for (NSInteger i = 0; i < 4; i++) {
UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds)*i, 0, CGRectGetWidth(self.view.bounds), 220)];
// 设置图片
[imageview setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg",(long)i]]];
[self.scrollview addSubview:imageview];
}
//设置图片的分页
[self.scrollview setPagingEnabled:YES];
//将图片水平面的横线隐藏
[self.scrollview setShowsHorizontalScrollIndicator:NO];
self.scrollview.delegate = self;
//设置滚动视图下面的点
self.pagecon = [[UIPageControl alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.scrollview.frame)-20, self.view.frame.size.width, 20)];
//设置的点数
[self.pagecon setNumberOfPages:4];
[self.pagecon setPageIndicatorTintColor:[UIColor blackColor]];
[self.view addSubview:self.pagecon];
self.edgesForExtendedLayout = UIRectEdgeNone;
self.automaticallyAdjustsScrollViewInsets = YES;
}
//调用 UIscrollview 的协议方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
[self.pagecon setCurrentPage:(NSInteger)(scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame))];
}
//封装的定时器
- (void)initTimer{
if (!self.timer) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(click) userInfo:nil repeats:YES];
//定时器会跑在标记为common modes的模式下,以上两种通用,像广告轮播等就会用到该模式。
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
/*self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(click) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
*/
}
}
-(void)click{
NSInteger pagecount = self.pagecon.currentPage + 1;
if (pagecount >= 4) {
pagecount = 0;
}
[self.scrollview setContentOffset:CGPointMake(pagecount * CGRectGetWidth(self.scrollview.frame), 0) animated:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
if (self.timer) {
//invalidate 废弃
[self.timer invalidate];
[self setTimer:nil];
}
}
//结束后返回第一张图片
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[self initTimer];
}