{
UIScrollView *_scroll;
UIPageControl *_pageControl;
}
- (void)viewDidLoad {
[super viewDidLoad];
//无限轮播:两种思路1.前加1后加1 2.三张imaview切换图片
//1.前加一后加一:(在轮播图片的总数上多创建2张图片放在轮播图的两端)
_scroll= [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 400)];
_scroll.contentSize=CGSizeMake(9 * [[UIScreen mainScreen] bounds].size.width, 400);
_scroll.backgroundColor= [UIColor yellowColor];
_scroll.pagingEnabled=YES;
_scroll.bounces=NO;
_scroll.delegate=self;
_scroll.showsHorizontalScrollIndicator=NO;
_scroll.showsVerticalScrollIndicator=NO;
[self.view addSubview:_scroll];
for(inti = 0; i < 9; i ++) {
UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(i *[[UIScreen mainScreen] bounds].size.width, 0, [[UIScreen mainScreen] bounds].size.width, 400)];
if(i == 0) {
imageview.image= [UIImage imageNamed:@"7.jpg"];
}elseif(i == 8){
imageview.image= [UIImage imageNamed:@"1.jpg"];
}else{
imageview.image= [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",i]];
}
[_scroll addSubview:imageview];
}
//初始偏移
[_scroll setContentOffset:CGPointMake([[UIScreen mainScreen]bounds].size.width, 0) animated:NO];
_pageControl= [[UIPageControl alloc] initWithFrame:CGRectMake(([[UIScreen mainScreen] bounds].size.width-100)/2.0, 370, 100, 30)];
_pageControl.numberOfPages= 7;
_pageControl.currentPageIndicatorTintColor= [UIColorblackColor];
_pageControl.pageIndicatorTintColor= [UIColorgrayColor];
_pageControl.currentPage= 0;
[self.view addSubview:_pageControl];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(change) userInfo:nil repeats:YES];
}
- (void)change {
///static int a=0;
// static int x=0;
static int i = 1;
i ++ ;
//animated 设置为YES
[_scroll setContentOffset:CGPointMake([[UIScreen mainScreen]bounds].size.width* i, 0) animated:YES];
// 7 1 2 3 4 5 6 7 1
if(i == 8) {
i = 1;
}
}
#pragma mark === 代理方法滚动结束调用的方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//导入滚动代理协议,设置self,写在滚动结束的代理方法中
//animated动画效果一定要是NO
//9 : 7 1 2 3 4 5 6 7 1
//当前偏移位置第几张图片
//如果是最后一张图片(也就是我们之前放的第一张展示的图片)
if(scrollView.contentOffset.x/[[UIScreenmainScreen]bounds].size.width== 8) {
[scrollView setContentOffset:CGPointMake([[UIScreenmainScreen]bounds].size.width, 0) animated:NO];
}
if(scrollView.contentOffset.x/[[UIScreen mainScreen]bounds].size.width== 0) {//最左边
[scrollView setContentOffset:CGPointMake(7*[[UIScreen mainScreen] bounds].size.width, 0) animated:NO];
}
_pageControl.currentPage= scrollView.contentOffset.x/[[UIScreen mainScreen]bounds].size.width- 1 ;
}