昨天有個(gè)需要要求像微博個(gè)人主頁(yè)的view交互方式那樣,(描述起來(lái)有點(diǎn)麻煩,具體請(qǐng)看下面的動(dòng)態(tài)效果)!在網(wǎng)上沒(méi)有找到實(shí)現(xiàn)方法,于是自己就探究了該交互的實(shí)現(xiàn)方式!
2016-11-09 22_19_42.gif
方法一:
先在self.view上添加一個(gè)tableView和一個(gè)topView,然后設(shè)置self.tableView.contentInset.top為topView的高度,然后在tableView的滾動(dòng)方法里移動(dòng)topView到相應(yīng)的位置,在合適的位置不在讓topView移動(dòng)即可!(先設(shè)置contentInset后添加代理的原因是contentInset會(huì)觸發(fā)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;
}
// 如果判斷下面的內(nèi)容,tableView向下滾動(dòng)時(shí),topView不會(huì)跟著移動(dòng)
// if (newConstant > 0) {
// newConstant = 0;
// }
self.topLayout.constant = newConstant;
}
方法二:
利用tableView的headerView的粘性.如果是在tableView的代理方法里設(shè)置headerView,當(dāng)滾動(dòng)到headerView的頂端后, headerView不會(huì)再跟隨cell一起滾動(dòng)!我們可以利用這個(gè)特性實(shí)現(xiàn)現(xiàn)在的需求!這個(gè)方式與我另一篇關(guān)于去除headerView粘性的文章內(nèi)容差不多!具體上代碼
- (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;
}