您的位置:首页 > 移动开发 > IOS开发

iOS TableView头视图根据偏移量下拉缩放的效果实现

2016-09-01 17:05 861 查看
在做项目时,一些TableView的地方会使用到下拉TableView让HeardView头视图随其偏移量的变化而变化,之前做过一次但没记录下来。现在做的时候总是遇到一些问题,比如下拉时是以原点向左右两边放大,这个只是效果问题。还有就是看到的视图确实变大了,但是会盖到下面的TableViewCell。开始以为是加在里面的视图变大,而TableViewHeardView没变大,我NSLog打印了一下两个视图的高度,发现是一样的,找不到问题了。

在网上找了一些相关的例子,各有各的做法,有的是根据偏移量来设置TableViewHeardView的缩放,有的是设置里面被我们设置为TableViewHeardView的那个视图的大小,都试了一下感觉还是不行,感觉缩放效果是有了的,但是拉大一点就会把下面的cell盖住。

之后自己摸索,调整后,我是用偏移量来控制里面的imageView的大小,imageView是我设置的HeardView的子视图,而heardView和TableViewheard的大小不会根据imageView变化,只是坐标变了,其实这是一种错觉,真实的效果是imageView坐标向左上方偏移,大小也变化,而heardView和TableViewheard没变大,但imageView变大的部分盖住他们的上方,让我们觉得heardView和TableViewheard也变大了,可以参考文章下面的逻辑图。

先看一看效果吧,一张是没下拉时的效果,一张是下拉时的效果。





可以看到imageView向四周变大了,而头像和昵称只是垂直方向位置变了,而大小没变。

这里用到的控件入下图



#define ScreenWidth [UIScreen mainScreen].bounds.size.width
在viewDidLoad里创建一下,

//========== 头视图创建与设置 ===========

imageHight = 250;

[self creatHeardView];

- (void)creatHeardView

{

headerView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, ScreenWidth, imageHight+50))];

//背景视图

heardImageView = [[UIImageView alloc] init];

heardImageView.frame = CGRectMake(0, 0, ScreenWidth, imageHight);

heardImageView.image = [UIImage imageNamed:@"backGround.jpg"];

[headerView addSubview:heardImageView];

//用户头像

personImageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth-30-60, imageHight-30, 60, 60)];

personImageView.layer.cornerRadius = CGRectGetWidth(personImageView.frame)/2;

personImageView.layer.masksToBounds = YES;

[headerView addSubview:personImageView];

//用户名

personNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(personImageView.frame)-200, CGRectGetMinY(personImageView.frame), 180, 30)];

personNameLabel.font = [UIFont systemFontOfSize:15];

personNameLabel.textColor = [UIColor whiteColor];

personNameLabel.textAlignment = NSTextAlignmentRight;

[headerView addSubview:personNameLabel];

//个人签名

introduceLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, CGRectGetMaxY(personImageView.frame), ScreenWidth-60, 20)];

introduceLabel.font = [UIFont systemFontOfSize:10];

introduceLabel.textColor = [UIColor grayColor];

introduceLabel.textAlignment = NSTextAlignmentRight;

[headerView addSubview:introduceLabel];

comTableView.tableHeaderView = headerView;//设置头视图

}

然后在TableView的滚动代理中有一个方法可以实时监测滚动偏移量,

#pragma mark - 滚动代理

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

{

CGFloat width = self.view.frame.size.width;
//
图片宽度

CGFloat yOffset = scrollView.contentOffset.y; //
偏移的y值,还要考虑导航栏的64哦

if (yOffset < 0) {//向下拉是负值,向上是正

CGFloat totalOffset = imageHight + ABS(yOffset);

CGFloat f = totalOffset / imageHight;//缩放比例

//拉伸后的图片的frame应该是同比例缩放。

heardImageView.frame = CGRectMake(- (width * f - width) / 2, yOffset, width * f, totalOffset);

}

}

逻辑图:



这样TableView的下拉缩放头视图功能就可以实现了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息