tableview自定义header

自定义tableView的header, 利用转换坐标系来达到header的停留与跟随

#import 

#define toolbarH 44

@interface ViewController () <UITableViewDelegate>
@property(nonatomic, weak) UITableView *tableView;
@property(nonatomic, weak) UIView *toolbar;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];


UITableView *tableView = [[UITableView alloc] init];
tableView.frame = self.view.bounds;
// 设置tableView的内边距的top位置为toolbar的高
tableView.contentInset = UIEdgeInsetsMake(toolbarH, 0, 0, 0);
tableView.delegate = self;
[self.view addSubview:tableView];
_tableView = tableView;

// 创建toolbar
CGFloat toolbarW = self.tableView.bounds.size.width;
UIView *toolbar = [[UIView alloc] init];
toolbar.frame = CGRectMake(0, -toolbarH, toolbarW, toolbarH);
toolbar.backgroundColor = [UIColor orangeColor];
[self.tableView addSubview:toolbar];
_toolbar = toolbar;
}

#pragma mark - UIScrollViewDelegate
// 模拟tableView plain模式的header停留
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// 存放新Y值
CGFloat newY = 0;
if (toolbarH + scrollView.contentOffset.y > 0) { // 向上拖拽偏移量减少 - 转换坐标系
// 转换坐标系
UIWindow *window = [UIApplication sharedApplication].windows.lastObject;
[window addSubview:self.toolbar];
newY = [self.tableView convertRect:self.tableView.bounds toView:window].origin.y;
} else { // 向下拖拽时偏移量增加 - toolBar跟随tableView
[self.tableView addSubview:self.toolbar];
newY = -toolbarH;
}
// 更新frame
CGRect frame = self.toolbar.frame;
frame.origin.y = newY;
self.toolbar.frame = frame;
}
@end