参考:http://blog.youkuaiyun.com/u011449777/article/details/25384405感谢该网友的帮助!
1、使用headerView注意事项:使用前要先注册以便复用:
static NSString *headerFooterViewReuseIdentifier = @"HeaderFooterViewReuseIdentifier";
[self.tableView registerClass:[HeadView class] forHeaderFooterViewReuseIdentifier:headerFooterViewReuseIdentifier];
//注意虽然函数的返回值写的是View类型的,但是应该返回UITableViewHeaderFooterView *型
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//初始化imageView.
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 5, 30, 30)];
if (self.isDown) {
imageView.frame = CGRectMake(290, 5, 30, 30);
}
imageView.image = [UIImage imageNamed:@"头像"];
imageView.backgroundColor = [UIColor redColor];
//重用headerView
HeadView *headerView = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:headerFooterViewReuseIdentifier];
//把imageView赋值给HeaderView的属性。
headerView.imageView = imageView;
return headerView;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// UITableView从UIScrollView继承了一个属性contentOffset,通过它,我们可以知道UITableView显示的左上角的偏移量。
CGPoint point = scrollView.contentOffset
//根据contentOffset获得顶部indexPath。
NSIndexPath *path = [self.tableView indexPathForRowAtPoint:point];
//通过UITableView在ios6新增的方法,我们就可以通过indexPath.section获得顶部的headerView。
HeadView *headerView = (HeadView *)[self.tableView headerViewForSection:path.section];
UIImageView *imageView = headerView.imageView;
//根据滚动方向的不同,头像的移动方向也不同。所以,我们要添加一个属性,来帮助我们判断滚动方向。
if ((point.y > self.lastPoint.y) && (imageView.frame.origin.x == 10)) {
self.isDown = NO;
[UIView animateWithDuration:toRightDuration animations: ^{
imageView.frame = CGRectMake(290, 5, 30, 30);
}];
}
else if ((point.y < self.lastPoint.y) && (imageView.frame.origin.x == 290)) {
self.isDown = YES;
[UIView animateWithDuration:toLeftDuration animations: ^{
imageView.frame = CGRectMake(10, 5, 30, 30);
}];
}
//把当前的point赋给self.lastPoint
self.lastPoint = point;
}
//contentOffset 内容相对于scrollview的坐标 //contentInset 内容相对于scrollview各个边的距离 //根据偏移量得到显示内容最右上角的坐标,然后根据坐标得到相应的indexpatch CGPoint point = scrollView.contentOffset; NSIndexPath *path = [self.tableView indexPathForRowAtPoint:point];
;//去掉UItableview headerview黏性(sticky) - (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat sectionHeaderHeight = 40; if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) { scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0); } else if (scrollView.contentOffset.y>=sectionHeaderHeight) { scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0); } }