首页 > 代码库 > IOS 图片轮播
IOS 图片轮播
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @end #import "ViewController.h" @interface ViewController ()<UIScrollViewDelegate> @property(nonatomic, strong) NSTimer *timer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIScrollView *sView = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 20, 300, 440)]; sView.contentSize = CGSizeMake(1200, 440); sView.pagingEnabled = YES; sView.showsHorizontalScrollIndicator = NO; sView.tag = 200; //循环创建添加4张图片 for (int i = 0; i < 4; i ++) { UIImageView *imgView = [[UIImageView alloc]init]; imgView.frame = CGRectMake(i*300, 0, 300, 440); imgView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i]]; [sView addSubview:imgView]; } [self.view addSubview:sView]; //创建书页控件 UIPageControl *pageControl = [[UIPageControl alloc]init]; pageControl.frame = CGRectMake( 100, 440, 120, 20); pageControl.numberOfPages = 4; pageControl.currentPage = 0; pageControl.tag = 100; [self.view addSubview:pageControl]; //设置scrollView的代理为当前类对象 sView.delegate = self; //添加定时器,使用scheuled方法创建的定时器,不需要用fird方法打开(自动开启的) [self addtimer]; } //添加定时器方法 -(void) addtimer{ _timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES]; //返回当前的消息循环对象 [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; } //删除定时器方法 -(void) deleteTimer{ [_timer invalidate]; _timer = nil; } -(void)nextPage{ int page = 0; UIPageControl *pControl = (UIPageControl *)[self.view viewWithTag:100]; if (pControl.currentPage == 3) { page = 0; }else{ page = pControl.currentPage + 1; } //计算滚动的位置 UIScrollView *sView = (UIScrollView *)[self.view viewWithTag:200]; CGFloat offsetX = page * sView.frame.size.width; CGPoint offset = CGPointMake(offsetX, 0); [sView setContentOffset:offset animated:YES]; } #pragma - mark UIScrollViewDelegate //监听滚动的位置,改变pageCotrol的currentPage的值. -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ UIPageControl *pControl = (UIPageControl *)[self.view viewWithTag:100]; CGFloat scrollW = scrollView.frame.size.width; int page = (scrollView.contentOffset.x + scrollW * 0.5 )/ scrollW; pControl.currentPage = page; } -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ [self deleteTimer]; } -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ [self addtimer]; } @end
IOS 图片轮播
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。