iOS 图片轮播图(自动滚动)

iOS 图片轮播图(自动滚动)

#import "DDViewController.h"

#define DDImageCount 5

@interface DDViewController ()<UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;

//定时器

@property (nonatomic,strong)NSTimer *timer;

@end

@implementation DDViewController

- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

// 设置一些固定的尺寸参数

CGFloat imageW = self.scrollView.frame.size.width;

CGFloat imageH = self.scrollView.frame.size.height;

CGFloat imageY = 0;

// 1.添加5张图片到scrollview中

for (int i=0; i<DDImageCount; i++) {

UIImageView *imageView = [[UIImageView alloc]init];

CGFloat imageX = i * imageW;

imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);

imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_0%d",i+1]];

[self.scrollView addSubview:imageView];

}

// 2.设置内容尺寸

CGFloat contenW = DDImageCount * imageW;

// 水平滚动

self.scrollView.contentSize = CGSizeMake(contenW, 0);

// 上下滚动

//    self.scrollView.contentSize = CGSizeMake(0, XXXX);

// 3.隐藏水平滚动条

self.scrollView.showsHorizontalScrollIndicator = NO;

// 4.分页

self.scrollView.pagingEnabled = YES;

// 5.设置pagecontrol的总页数

self.pageControl.numberOfPages = DDImageCount;

// 6.添加定时器(每隔2秒调用一次self 的 nextImage的方法)

[self addTimer];

}

//添加定时器

- (void)addTimer

{

self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];

// 设置主线程。

[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

}

//移除定时器

- (void)removertimer

{

[self.timer invalidate];

self.timer = nil;

}

- (void)nextImage

{

// 增加pagecontrol的页码

int page = 0;

if (self.pageControl.currentPage == DDImageCount - 1) {

page = 0;

}else{

page = self.pageControl.currentPage + 1;

}

// 计算scrollview滚动位置

CGFloat offsetX = page * self.scrollView.frame.size.width;

CGPoint offset = CGPointMake(offsetX, 0);

[self.scrollView setContentOffset:offset animated:YES];

}

//ScrollView代理方法。使用时要设置代理(self.delgate = self)或者在图片上进行设置

/**

*  当scrollView正在滚动就会调用

*/

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

{

// 根据scrollview的滚动位置决定pagecontrol显示第几页

CGFloat scrollW = scrollView.frame.size.width;

int page = (scrollView.contentOffset.x + scrollW * 0.5) / scrollW;

self.pageControl.currentPage = page;

}

/**

*  开始拖拽的时候调用

*/

- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView

{

// 停止定时器(一旦定时器停止了,就不能再使用)

[self removertimer];

}

/**

*  停止拖拽的时候调用

*/

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate

{

//开启定时器

[self addTimer];

}

上一篇:SQL sysobjects 表 详解


下一篇:jmeter5.1在windows(含插件安装)及linux环境下安装