iOS 简单的轮播
-(UIScrollView*)scrollV{
if(!_scrollV) {
_scrollV= [[UIScrollViewalloc]initWithFrame:self.view.frame];
_scrollV.pagingEnabled = YES;
_scrollV.bounces=NO;
_scrollV.delegate=self;
_scrollV.contentSize=CGSizeMake(WIDTH*imgArr.count,HEIGHT) ;
for(inti =0; i
UIImageView*imgV = [[UIImageViewalloc]initWithFrame:CGRectMake(WIDTH*i,0,WIDTH,HEIGHT)];
imgV.image= [UIImageimageNamed:imgArr[i]];
[_scrollVaddSubview:imgV];
if(i ==imgArr.count-1) {
imgV.userInteractionEnabled=YES;
UIButton*btn = [[UIButtonalloc]initWithFrame:CGRectMake((WIDTH-100)/2,560,100,100)];
btn.backgroundColor= [UIColorblackColor];
btn.layer.cornerRadius=10;
btn.clipsToBounds=YES;
[btnsetTitle:@"立即体验"forState:UIControlStateNormal];
[btnaddTarget:self action:@selector(Click) forControlEvents:UIControlEventTouchUpInside];
[imgVaddSubview:btn];
}
}
}
return _scrollV;
}
-(UIPageControl *)pageC{
if(!_pageC) {
_pageC= [[UIPageControlalloc]initWithFrame:CGRectMake((WIDTH-100)/2,600,100,30)];
_pageC.numberOfPages = imgArr.count;
_pageC.pageIndicatorTintColor = [UIColor blackColor];
_pageC.currentPageIndicatorTintColor = [UIColor redColor];
[_pageC addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
}
return _pageC;
}
-(void)Click{
ViewController *vc = [ViewController new];
// 有导航栏用 push
// [self.navigationController pushViewController:vc animated:YES];
[self presentViewController:vc animated:YES completion:^{
nil;
}];
}
//pageControl 点击事件,点击PageCt 改变滚动视图的偏移量
-(void)valueChanged:(UIPageControl*)pc
{
NSIntegercurrentPage = pc.currentPage;
//设置scrollV的偏移量
[_scrollV setContentOffset:CGPointMake(currentPage * WIDTH,0) animated:YES];
}
//滚动视图停止滚动的时候
-(void)scrollViewDidScroll:(UIScrollView*)scrollView
{
NSLog(@"滚动的时候会调用");
_pageC.currentPage = scrollView.contentOffset.x/WIDTH;
}
//创建定时器
- (void)startTimer {
_timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(ChangeImage)userInfo:nil repeats:YES];
// 调整timer 的优先级
NSRunLoop*mainLoop = [NSRunLoopmainRunLoop];
[mainLoopaddTimer:_timer forMode:NSRunLoopCommonModes];
}
//定时器方法,定时滚动图片
-(void)ChangeImage{
if (self.pageC.currentPage==imgArr.count-2) {
[selfstopTimer];
}
[_scrollV setContentOffset:CGPointMake((self.pageC.currentPage+1)*WIDTH, 0) animated:YES];
}
/**
手指开始拖动的时候, 就让计时器停止
*/
- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView {
[self stopTimer];
}
/**
手指离开屏幕的时候, 就让计时器开始工作
*/
- (void)scrollViewWillEndDragging:(UIScrollView*)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inoutCGPoint*)targetContentOffset {
[self startTimer];
}
//停止定时器
- (void)stopTimer
{
[self.timer invalidate];
self.timer=nil;
}