昨天有个需要要求像微博个人主页的view交互方式那样,(描述起来有点麻烦,具体请看下面的动态效果)!在网上没有找到实现方法,于是自己就探究了该交互的实现方式!
![](https://img.haomeiwen.com/i1429831/f68c8489f0a01339.gif)
方法一:
先在self.view上添加一个tableView和一个topView,然后设置self.tableView.contentInset.top为topView的高度,然后在tableView的滚动方法里移动topView到相应的位置,在合适的位置不在让topView移动即可!(先设置contentInset后添加代理的原因是contentInset会触发scrollViewDidScroll!)
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.contentInset = UIEdgeInsetsMake(160, 0, 0, 0);
self.tableView.dataSource = self;
self.tableView.delegate = self;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGFloat newConstant = -scrollView.contentOffset.y - 160;
if (newConstant < -130) {
newConstant = -130;
}
// 如果判断下面的内容,tableView向下滚动时,topView不会跟着移动
// if (newConstant > 0) {
// newConstant = 0;
// }
self.topLayout.constant = newConstant;
}
方法二:
利用tableView的headerView的粘性.如果是在tableView的代理方法里设置headerView,当滚动到headerView的顶端后, headerView不会再跟随cell一起滚动!我们可以利用这个特性实现现在的需求!这个方式与我另一篇关于去除headerView粘性的文章内容差不多!具体上代码
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat sectionHeaderHeight = 130;
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);
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 160)];
view.backgroundColor = [UIColor redColor];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 130, self.view.frame.size.width, 30)];
label.textAlignment = NSTextAlignmentCenter;
label.text = @"haha";
[view addSubview:label];
return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 160;
}
网友评论