美文网首页
仿饿了么首页滑动效果[1]

仿饿了么首页滑动效果[1]

作者: King_mr | 来源:发表于2017-10-28 09:48 被阅读0次
首页.gif

如图所示,首先已知的是有一个 UITableView,在下拉的时候顶端的蓝色可以跟随 tableView 一起下拉刷新! 上拉时搜索框会变成一个导航的样子,并且隐藏上面的地址和天气 UI. 之前看了好多次不知道是如何实现的,百度了一圈后算是知道了.(这个视觉效果太具有欺骗性了)

蓝色区域我分为两个 View 做的,顶部的搜索框以上是一个 View, 以下是一个 View (包括下面的白色区域,也就是 cell 以上).

首先创建两个 View,_navigationView添加到根视图上作为导航用,_headerView添加到 tableView上作为类似区头效果.
在滑动时_navigationView会向上移动来适配导航高度,并且会遮盖_headerView

 _navigationView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120)];
    _navigationView.backgroundColor = [UIColor orangeColor];
//    _navigationView.alpha = 1;
    [self.view addSubview:_navigationView];
    
    
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, -kHeaderHeight, SCREEN_WIDTH, kHeaderHeight)];
    _headerView.backgroundColor = [UIColor redColor];
//    _headerView.alpha = 1;
    [_tableView addSubview:_headerView];

然后是创建 tableView 了
由于_headerView是添加在 tableView的top,所以需要用UIEdgeInsetsMake这个属性来改变 cell 的 top, 也就是_headerView的高度加_navigationView的高度(76和上面的120不一样,但确实是_navigationView的高度,因为我是在 iPhone X 上适配的,刘海有44的高度,所以120-44=76)

_tableView = [[UITableView alloc]init];
    _tableView.frame = CGRectMake(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    _tableView.separatorColor = [UIColor greenColor];
    // 隐藏滑动条
    _tableView.showsVerticalScrollIndicator = NO;
    // 设置表格的间隔
    _tableView.contentInset = UIEdgeInsetsMake(kHeaderHeight + 76, 0, 0, 0);

紧接着就是滑动效果了
通过 tableview 的滑动方法,让 View 跟随滑动:
这部分我只是让 _navigationView 在滑动的时候改变其Y 轴以适配导航栏高度

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offSetY = scrollView.contentOffset.y + scrollView.contentInset.top;

//            //iPhone X 下 View 滑动后的高度
            CGFloat minY = 32 ;
//            // 设置顶部视图Y轴坐标
            _navigationView.y = -MIN(offSetY, minY);
//            // 计算透明度
            CGFloat alpha = 0 + offSetY / minY;
            _textF.alpha = alpha;
    
    if (offSetY < 0)
    {
        //View 跟随 TableView 滑动下拉
//        _navigationView.y = kHeaderHeight - offSetY;
//        _navigationView.h = kHeaderHeight - offSetY;
    }
}
首页.gif

效果就是这样了
不过还有一种方法也可以做到
如果不想让_headerView添加到 tableview
那么还可以这样,达到的效果是一样的,而且不用再修改 cell 的 top 了

    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    // 设置header
    _tableView.tableHeaderView = header;
    _tableView.tableHeaderView.backgroundColor = [UIColor blueColor];

开始感觉好难,做出来后觉得真的是只有想不到,没有做不到!
我也是看了别人的代码后才慢慢改的,我还是太菜了.
有问题的可以留言,如果有需要代码的 稍后我会上传到 GitHub

相关文章

网友评论

      本文标题:仿饿了么首页滑动效果[1]

      本文链接:https://www.haomeiwen.com/subject/bfvjpxtx.html