iOS如何做可拉伸头部

1.通过xib做

我们经常需要让tableview上的headview可以通过下拉tableview进行缩放,达到一种弹动的效果。

首先我们需要一个headview,这个headview需要使用AutoLayout,或者说你用Masonry也行。

下面用的是xib的方法,我还没尝试用过Masonry,不过既然都是约束,肯定也都能实现的。

你需要把一个imageview的高度延伸到view的顶上,然后向下拖一个与headview顶部的约束,比如说这样:

image

然后在tableview里:

self.tableHeaderView = xxx

这里的xxx也就是说跟xib关联的view。

然后你需要实现一个方法:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGFloat offset = scrollView.contentOffset.y;

}

这个方法是scrollview里的,tableview实际上就是继承了scrollview。而这个offset是scrollview的偏移量,也就是说,你要做的就是通过这个offset的偏移量,以一种比例来拉伸headview上的imageview。

注意,这里根据offset改变控件的frame一定要是改变imageview的frame,如果你改变的是headview的frame,就会出现headview拉伸的过程中覆盖了底下的cell,这样是不对的。因为headview下的cell应该是在拉伸的过程中就往下或者往上滑动的。

2.通过纯代码做

通过纯代码做有一点小技巧
我们首先需要创建一个imageView放在vc的view上,这个originFrame之后要用

imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"背景"]];
imageView.frame = CGRectMake(0, 64,[UIScreen mainScreen].bounds.size.width, 200);
originFrame = imageView.frame;
[self.view addSubview:imageView];

然后在把tableView放在vc的view上,然后把tableView的背景设为clearColor

UITableView *tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64)];
tableview.delegate = self;
tableview.dataSource = self;
tableview.showsVerticalScrollIndicator = false;
tableview.backgroundColor = [UIColor clearColor];
[self.view addSubview:tableview];

然后效果应该是这样的

01@2x.png

接下来要让tableView不能盖住那个imageView,做法是

UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200)];
headerView.backgroundColor = [UIColor clearColor];
tableview.tableHeaderView = headerView;

我这个imageView的高度是200,所以我给了个tableHeaderView设为clearColor

效果是这样的

02@2x.png

那拖动拉伸效果是写在scrollViewDidScroll里的

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGFloat offset = scrollView.contentOffset.y;

if (offset > 0) {
    //复合语句
    imageView.frame = ({
        CGRect frame = originFrame;
        frame.origin.y = originFrame.origin.y - offset;
        frame;
    });
}else {
    imageView.frame = ({
        CGRect frame = originFrame;
        frame.size.height = originFrame.size.height - offset;
        frame.size.width = originFrame.size.width - offset;
        frame.origin.x = originFrame.origin.x - (frame.size.width - originFrame.size.width) / 2;
        frame;
    });
}
}

originFrame在这里用到了,因为imageView的frame时刻在变,所以要用一个初始值originFrame

最终效果

IMG_0567.TRIM.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。