//封裝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];
//設(shè)置滾動(dòng)視圖的長(zhǎng)度
[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)];
// 設(shè)置圖片
[imageview setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg",(long)i]]];
[self.scrollview addSubview:imageview];
}
//設(shè)置圖片的分頁
[self.scrollview setPagingEnabled:YES];
//將圖片水平面的橫線隱藏
[self.scrollview setShowsHorizontalScrollIndicator:NO];
self.scrollview.delegate = self;
//設(shè)置滾動(dòng)視圖下面的點(diǎn)
self.pagecon = [[UIPageControl alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.scrollview.frame)-20, self.view.frame.size.width, 20)];
//設(shè)置的點(diǎn)數(shù)
[self.pagecon setNumberOfPages:4];
[self.pagecon setPageIndicatorTintColor:[UIColor blackColor]];
[self.view addSubview:self.pagecon];
self.edgesForExtendedLayout = UIRectEdgeNone;
self.automaticallyAdjustsScrollViewInsets = YES;
}
//調(diào)用 UIscrollview 的協(xié)議方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
[self.pagecon setCurrentPage:(NSInteger)(scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame))];
}
//封裝的定時(shí)器
- (void)initTimer{
if (!self.timer) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(click) userInfo:nil repeats:YES];
//定時(shí)器會(huì)跑在標(biāo)記為common modes的模式下,以上兩種通用吕粗,像廣告輪播等就會(huì)用到該模式寓涨。
[[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];
}
}
//結(jié)束后返回第一張圖片
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[self initTimer];
}