iOS开发UI篇—UIScrollView控件实现图片轮播=

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

iOS开发UI篇—UIScrollView控件实现图片轮播iOS开发UI篇—UIScrollView控件实现图片轮播一、实现效果实现图片的自动轮播二、实现代码storyboard中布局代码:1#importYYViewController.h23@interfaceYYViewController()UIScrollViewDelegate4@property(weak,nonatomic)IBOutletUIScrollView*scrollview;5/**6*页码7*/8@property(weak,nonatomic)IBOutletUIPageControl*pageControl;910@property(nonatomic,strong)NSTimer*timer;11@end1213@implementationYYViewController1415-(void)viewDidLoad16{17[superviewDidLoad];1819//图片的宽20CGFloatimageW=self.scrollview.frame.size.width;21//CGFloatimageW=300;22//图片高23CGFloatimageH=self.scrollview.frame.size.height;24//图片的Y25CGFloatimageY=0;26//图片中数27NSIntegertotalCount=5;28//1.添加5张图片29for(inti=0;itotalCount;i++){30UIImageView*imageView=[[UIImageViewalloc]init];31//图片X32CGFloatimageX=i*imageW;33//设置frame34imageView.frame=CGRectMake(imageX,imageY,imageW,imageH);35//设置图片36NSString*name=[NSStringstringWithFormat:@img_0%d,i+1];37imageView.image=[UIImageimageNamed:name];38//隐藏指示条39self.scrollview.showsHorizontalScrollIndicator=NO;4041[self.scrollviewaddSubview:imageView];42}4344//2.设置scrollview的滚动范围45CGFloatcontentW=totalCount*imageW;46//不允许在垂直方向上进行滚动47self.scrollview.contentSize=CGSizeMake(contentW,0);4849//3.设置分页50self.scrollview.pagingEnabled=YES;5152//4.监听scrollview的滚动53self.scrollview.delegate=self;5455[selfaddTimer];56}5758-(void)nextImage59{60intpage=(int)self.pageControl.currentPage;61if(page==4){62page=0;63}else64{65page++;66}6768//滚动scrollview69CGFloatx=page*self.scrollview.frame.size.width;70self.scrollview.contentOffset=CGPointMake(x,0);71}7273//scrollview滚动的时候调用74-(void)scrollViewDidScroll:(UIScrollView*)scrollView75{76NSLog(@滚动中);77//计算页码78//页码=(contentoffset.x+scrollView一半宽度)/scrollView宽度79CGFloatscrollviewW=scrollView.frame.size.width;80CGFloatx=scrollView.contentOffset.x;81intpage=(x+scrollviewW/2)/scrollviewW;82self.pageControl.currentPage=page;83}8485//开始拖拽的时候调用86-(void)scrollViewWillBeginDragging:(UIScrollView*)scrollView87{88//关闭定时器(注意点;定时器一旦被关闭,无法再开启)89//[self.timerinvalidate];90[selfremoveTimer];91}9293-(void)scrollViewDidEndDragging:(UIScrollView*)scrollViewwillDecelerate:(BOOL)decelerate94{95//开启定时器96[selfaddTimer];97}9899/**100*开启定时器101*/102-(void)addTimer{103104self.timer=[NSTimerscheduledTimerWithTimeInterval:1target:selfselector:@selector(nextImage)userInfo:nilrepeats:YES];105106}107/**108*关闭定时器109*/110-(void)removeTimer111{112[self.timerinvalidate];113}114@end提示:以下两个属性已经和storyboard中的控件进行了连线。@property(weak,nonatomic)IBOutletUIScrollView*scrollview;@property(weak,nonatomic)IBOutletUIPageControl*pageControl;补充:定时器NSTimer定时器适合用来隔一段时间做一些间隔比较长的操作NSTimeInterval:多长多件操作一次target:操作谁selector:要操作的方法userInfo:传递参数repeats:是否重复self.timer=[NSTimerscheduledTimerWithTimeInterval:1target:selfselector:@selector(nextImage)userInfo:nilrepeats:YES];

1 / 5
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功