页面层级是先添加头部图片imageView,然后添加tableView,设置其tableHeaderView的frame与imageHeader一致,记录imageHeader的初始frame.
- (void)initSubViews
{
self.imageHeader = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width * 3 / 4)];
self.imageHeader.image = [UIImage imageNamed:@"image"];
frameF = self.imageHeader.frame;
[self.view addSubview:self.imageHeader];
[self.view addSubview:self.tableView];
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width * 3/ 4)];
headerView.backgroundColor = [UIColor clearColor];
self.tableView.tableHeaderView = headerView;
}
懒加载tableView
- (UITableView *)tableView
{
if (!_tableView) {
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view. bounds.size.width, self.view.bounds.size.height)];
_tableView.dataSource = self;
_tableView.delegate = self;
_tableView.backgroundColor = [UIColor clearColor];
}
return _tableView;
}
重点在于UIScrollView的代理方法
#pragma mark - UIScrollView Delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//frameF为最初image的位置
CGFloat offset = scrollView.contentOffset.y;
if (offset > 0) {
CGRect frame = frameF;
frame.origin.y = frameF.origin.y - offset;
self.imageHeader.frame = frame;
}else{
CGRect frame = frameF;
frame.size.height = frameF.size.height - offset;
frame.size.width = frame.size.height * 4 / 3;
frame.origin.x = frameF.origin.x - (frame.size.width - frameF.size.width) / 2;
self.imageHeader.frame = frame;
}
}
一切搞定。
网友评论