美文网首页
iOS 顶部自动轮播图

iOS 顶部自动轮播图

作者: 燃_ec9b | 来源:发表于2017-11-23 10:55 被阅读14次

@interfaceMainViewController()

@property(nonatomic,strong)UIScrollView*scrollView;

@property(nonatomic,strong)UIPageControl*pageControl;

@property(nonatomic,strong)NSTimer*timer;

@end

@implementationMainViewController

- (void)viewDidLoad {

[superviewDidLoad];

// Do any additional setup after loading the view.

[self.viewsetBackgroundColor:[UIColorwhiteColor]];

self.scrollView= [[UIScrollViewalloc]initWithFrame:CGRectMake(0,64,CGRectGetWidth(self.view.bounds),220)];

[self.scrollViewsetDelegate:self];

[self.viewaddSubview:self.scrollView];

NSIntegerwidth =CGRectGetWidth(self.view.bounds);

[self.scrollViewsetContentSize:CGSizeMake(width *5,0)];

for(NSIntegeri =0; i<5; i++) {

UIImageView*imgView = [[UIImageViewalloc]initWithFrame:CGRectMake(width * i ,0, width,220)];

[imgViewsetImage:[UIImageimageNamed:[NSStringstringWithFormat:@"timg-%zd",i]]];

[self.scrollViewaddSubview:imgView];

}

[self.scrollViewsetPagingEnabled:YES];

[self.scrollViewsetShowsHorizontalScrollIndicator:NO];

self.pageControl= [[UIPageControlalloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(self.scrollView.frame) -20, width,20)];

[self.pageControlsetPageIndicatorTintColor:[UIColorblackColor]];

[self.pageControlsetNumberOfPages:5];

[self.viewaddSubview:self.pageControl];

[selfinitTimer];

}

//将定时器的初始化封装在一个方法中方便多次调用

- (void)initTimer{

//判断是否存在定时器如果不存在则初始化

if(!self.timer) {

self.timer= [NSTimerscheduledTimerWithTimeInterval:2target:selfselector:@selector(scrollImage)userInfo:nilrepeats:YES];

// NSRunLoop系统默认的值为Defult当多个任务在UI主线程中运行的时候会影响定时器

[[NSRunLoopcurrentRunLoop]addTimer:self.timerforMode:NSRunLoopCommonModes];

}

}

//定时器的任务

- (void)scrollImage{

//获取当前为第几张图

NSIntegercurrentPage =self.pageControl.currentPage+1;

//判断如果当前为为最后一张或者大于最后一张的时候滚动视图会到第一张图

if(currentPage >=5) {

currentPage =0;

}

//滚动视图的偏移量x为当前的页数*滚动视图的宽度

[self.scrollViewsetContentOffset:CGPointMake(currentPage *CGRectGetWidth(self.scrollView.frame),0)animated:YES];

}

//将滚动视图与分页控件联动

- (void)scrollViewDidScroll:(UIScrollView*)scrollView{

//滚动视图横向偏移量/滚动视图的宽度

[self.pageControlsetCurrentPage:(NSInteger)(scrollView.contentOffset.x/CGRectGetWidth(scrollView.frame))];

}

//开始手动拖拽的时候销毁定时器

- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView{

if(self.timer) {

[self.timerinvalidate];

[selfsetTimer:nil];

}

}

//结束手动拖拽的时候重新创建定时器

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

[selfinitTimer];

}

相关文章

网友评论

      本文标题:iOS 顶部自动轮播图

      本文链接:https://www.haomeiwen.com/subject/ckmkpxtx.html