iOS实现图片自动切换效果
程序员文章站
2023-02-22 15:49:29
本文实例为大家分享了ios实现图片自动切换的具体代码,供大家参考,具体内容如下#import "viewcontroller.h"#define imageviewcount 5 @interface...
本文实例为大家分享了ios实现图片自动切换的具体代码,供大家参考,具体内容如下
#import "viewcontroller.h" #define imageviewcount 5 @interface viewcontroller ()<uiscrollviewdelegate> @property (weak, nonatomic) iboutlet uiscrollview *imagescrollview; @property (weak, nonatomic) iboutlet uipagecontrol *imageviewpagecontrol; @property (strong, nonatomic) nstimer *timer; @end @implementation viewcontroller - (void)viewdidload { [super viewdidload]; [self addimageview2scrollview]; self.imagescrollview.contentsize = cgsizemake(self.imagescrollview.frame.size.width * imageviewcount, 0); self.imagescrollview.delegate = self; self.imagescrollview.pagingenabled = yes;//uiscrollview支持拖动分页 self.imageviewpagecontrol.numberofpages = imageviewcount; [self addscrolltimer]; } - (void)rotatepic{ int currentpageindex = self.imageviewpagecontrol.currentpage; if(++currentpageindex == 5){ currentpageindex = 0; } cgfloat offsetx = currentpageindex * self.imagescrollview.frame.size.width; [uiview animatewithduration:1 animations:^{ self.imagescrollview.contentoffset = cgpointmake(offsetx, 0); }]; } /**添加图片到imagescrollview*/ - (void)addimageview2scrollview{ cgfloat imagewidth = self.imagescrollview.frame.size.width; cgfloat imageheight = self.imagescrollview.frame.size.height; for(int i = 0;i <= imageviewcount;i++){ uiimageview *imageinscroll = [[uiimageview alloc] init]; imageinscroll.frame = cgrectmake(i * imagewidth, 0, imagewidth, imageheight); imageinscroll.image = [uiimage imagenamed:[nsstring stringwithformat:@"img_%02d",i + 1]]; [self.imagescrollview addsubview:imageinscroll]; } } // 正滚动时执行 - (void)scrollviewdidscroll:(uiscrollview *)scrollview{ cgfloat offx = self.imagescrollview.contentoffset.x;//(0,0)距离content内部左上顶点的x轴长度 nslog(@"~~~~~~~%f ^^^^^^%f", offx, self.imagescrollview.frame.size.width); int currentpageindex = (offx + .5f * self.imagescrollview.frame.size.width) / self.imagescrollview.frame.size.width; self.imageviewpagecontrol.currentpage = currentpageindex; } - (void)addscrolltimer{ self.timer = [nstimer timerwithtimeinterval:2 target:self selector:@selector(rotatepic) userinfo:nil repeats:yes]; [[nsrunloop mainrunloop] addtimer:self.timer formode:nsrunloopcommonmodes]; } - (void)removescrolltimer{ [self.timer invalidate];//释放定时器 self.timer = nil; } // 开始准备滚动时执行 移除定时滚动操作 - (void)scrollviewwillbegindragging:(uiscrollview *)scrollview{ nslog(@"~~~scrollviewwillbegindragging"); [self removescrolltimer]; } // 结束滚动后执行 添加定时滚动操作 - (void)scrollviewdidenddragging:(uiscrollview *)scrollview willdecelerate:(bool)decelerate{ nslog(@"~~~scrollviewdidenddragging"); [self addscrolltimer]; } @end
对uiscrollview的运用,以上代码中有详细注释,需注意2点:
1.注意设置contentsize属性。其中contentsize表示scroll内容尺寸大小
2.注意设置代理uiscrollviewdelegate,才可调用其中的方法
对于定时器nstimer的运用需注意
1.在线程的loop中添加定时器
2.注意使用完成回收nstimer
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 泡面,宅男的最爱
下一篇: iOS自定义日期选择器