#import "ShopViewController.h"#import "ShopCollectionViewCell.h"@interface ShopViewController (){
UIScrollView *scroll;
UIPageControl *page;
NSTimer *timer;
NSArray *arr;
UICollectionView *shop;
UITableView *tv;
}
@end
@implementation ShopViewController
- (void)viewDidLoad {
[super viewDidLoad];
UISearchBar *search = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
//设置提示文字
search.placeholder = @"大家正在搜索: 皇家马德里";
[self.view addSubview:search];
self.edgesForExtendedLayout = UIRectEdgeNone;
self.automaticallyAdjustsScrollViewInsets = YES;
self.view.backgroundColor = [UIColor lightGrayColor];
scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 30, CGRectGetWidth(self.view.bounds), 200)];
scroll.delegate = self;
[self.view addSubview:scroll];
NSInteger width = CGRectGetWidth(self.view.bounds);
[scroll setContentSize:CGSizeMake(width * 5, 0)];
for (NSInteger i = 0; i<5; i++) {
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(width * i , 0, width, scroll.frame.size.height)];
//创建图片数组
arr = @[[UIImage imageNamed:@"Q1.jpg"],[UIImage imageNamed:@"B55.jpg"],[UIImage imageNamed:@"Y3.jpg"],[UIImage imageNamed:@"C9.jpg"],[UIImage imageNamed:@"K.jpg"]];
//将图片添加到图片框上
imgView.image = arr[i];
[scroll addSubview:imgView];
}
[scroll setPagingEnabled:YES];
[scroll setShowsHorizontalScrollIndicator:NO];
page = [[UIPageControl alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(scroll.frame) - 20, width, 20)];
[page setPageIndicatorTintColor:[UIColor blackColor]];
[page setNumberOfPages:5];
[self.view addSubview:page];
// 将定时器的初始化封装在一个方法中 方便多次调用
- (void)initTimer{
// 判断是否存在定时器如果不存在则初始化
if (!timer) {
timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scrollImage) userInfo:nil repeats:YES];
// NSRunLoop 系统默认的值为 Defult 当多个任务在 UI 主线程中运行的时候会影响定时器
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
}
// 定时器的任务
- (void)scrollImage{
// 获取当前为第几张图
NSInteger currentPage = page.currentPage + 1;
// 判断如果当前为为最后一张或者大于最后一张的时候滚动视图会到第一张图
if (currentPage >= 5) {
currentPage = 0;
}
// 滚动视图的偏移量 x 为当前的页数*滚动视图的宽度
[scroll setContentOffset:CGPointMake(currentPage * CGRectGetWidth(scroll.frame), 0) animated:YES];
}
// 将滚动视图与分页控件联动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
[page setCurrentPage:(NSInteger)(scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame))];
}
// 开始手动拖拽的时候销毁定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
if (timer) {
[timer invalidate];
}
}
// 结束手动拖拽的时候重新创建定时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[self initTimer];
}