#import <UIKit/UIKit.h> @interface YLFisrtViewController : UIViewController<UIScrollViewDelegate> @end
.m文件:
定义需要用到的变量:
NSArray * imageArr;//图片路径字符串数组 UIScrollView * scrollView;//滚动view UIPageControl * pageControl;//pageView BOOL Tend;//是否需要从头重新播放
一:实现手动滚动效果:
给self.view中添加一个scrollView
- (void)viewDidLoad{ [self initImgArr]; [self initScrollView]; [self.view addSubview:scrollView]; } -(void)initScrollView{ scrollView=[[UIScrollViewalloc]initWithFrame:CGRectMake(0, 0, kDeviceWidth,kDeviceHeight/3*2)]; scrollView.contentSize=CGSizeMake(kDeviceWidth*imageArr.count,kDeviceHeight/3*2); scrollView.delegate=self; scrollView.scrollEnabled=YES; for(int i=0;i<imageArr.count;i++){ UIImageView * firstImg=[[UIImageViewalloc]initWithImage:[UIImageimageNamed:[imageArrobjectAtIndex:i]]]; firstImg.frame=CGRectMake(kDeviceWidth*i, 0, kDeviceWidth, kDeviceHeight/3*2); [scrollView addSubview:firstImg]; } } -(void)initImgArr{ imageArr=@[@"gallery_1.png",@"gallery_2.png",@"gallery_3.png",@"gallery_4.png"]; }
如上就可以设置一个滚动图片的效果了;正在滚动的效果
第二步,加UIPageControl,做翻页效果,即产生白点
//在viewDidLoad方法里添加 [selfinitPageControl]; [self addSubview:pageControl]; //方法实现如下: -(void)initPageControl{ pageControl=[[UIPageControlalloc]initWithFrame:CGRectMake(kDeviceWidth/2-10, kDeviceHeight/3*2-20, 20, 20)]; pageControl.numberOfPages=imageArr.count; pageControl.currentPage=0; [pageControladdTarget:selfaction:@selector(changePage:) forControlEvents:UIControlEventValueChanged]; } //可以不要下面这个方法,此方法是手动点击白点的时候跳转相应页面视图 -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ int page=scrollView.contentOffset.x/kDeviceWidth; pageControl.currentPage=page; } //并且记得在手动滚动的时候更改pageControl的页码 -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ int page=scrollView.contentOffset.x/kDeviceWidth; pageControl.currentPage=page; }
如图:滚动条和页面滚动点都在
第三步就是做一个定时任务自动翻转
//启动定时任务 [NSTimerscheduledTimerWithTimeInterval:5target:selfselector:@selector(handleSchedule) userInfo:nilrepeats:YES]; 定时任务方法调用:(注意计算好最后一页循环滚动) -(void)handleSchedule{ ++pageControl.currentPage; if(Tend){ [scrollViewsetContentOffset:CGPointMake(0, 0) animated:YES]; pageControl.currentPage=0; }else{ [scrollViewsetContentOffset:CGPointMake(pageControl.currentPage*kDeviceWidth, 0) animated:YES]; } if (pageControl.currentPage==pageControl.numberOfPages-1) { Tend=YES; }else{ Tend=NO; }
scrollView.showsHorizontalScrollIndicator=NO;//有了白点了,不需要显示水平滑动线
scrollview.showsVerticalScrollIndicator = NO;//设置竖直滚动条是否出现
scrollview.showsHorizontalScrollIndicator = NO;//设置水平滚动条是否出现