@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
//设置scrollview
UIScrollView *_scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 20,VIEW_WIDTH , 261)]; //屏幕宽度
//设置内容大小
_scrollView.contentSize = CGSizeMake(VIEW_WIDTH*4,261);
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.delegate = self; //设置代理
_scrollView.pagingEnabled = YES; //分页
//设置图片
for (int i = 0; i<4; i++)
{
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(VIEW_WIDTH*i, 0, VIEW_WIDTH, 261)];
//设置图片
NSString *name = [NSString stringWithFormat:@"background%d",i+1];
imageView.image=[UIImage imageNamed:name];
[_scrollView addSubview:imageView];
}
//将滑动视图添加到表视图上
self.tableView.tableHeaderView = _scrollView;
UIPageControl *pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 230, VIEW_WIDTH, 30)];
pageControl.numberOfPages = 4;
pageControl.tag = 101;
[self.view addSubview:pageControl];
}
#pragma mark - scrollView Delegate
// scrollview 减速停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
if ([scrollView isMemberOfClass:[UITableView class]])
{
NSLog(@"scrollViewDidEndDecelerating %@",scrollView);
}
else{
//scrollView的偏移量,x,y值
int current = scrollView.contentOffset.x/VIEW_WIDTH;
UIPageControl *pageControl = (UIPageControl *)[self.view viewWithTag:101]; //类型强转,查找
pageControl.currentPage = current;
// NSLog(@"scrollViewDidEndDecelerating %@",scrollView);
NSLog(@"%f",scrollView.contentOffset.x);//打印偏移量值
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:@"row :%ld",(long)indexPath.row];
return cell;
}