巧妙实现悬浮tableviewHeaderView方法

效果图如下:

《巧妙实现悬浮tableviewHeaderView方法》 红色区域为headerView

核心思路

将自定义的headerView放在tabView 的上面,而不是作为tableView.tableHeaderView(即headerView和tableView平级,都添加到viewController的view上),然后设置tableView的contentInset为合适的值,在tableView滑动的时候,动态改变view的位置或者大小,使这个headerView看起来就像是有了悬浮功能的tableView.tableHeaderView。

核心代码如下:

mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
mainTable.delegate = self;
mainTable.dataSource = self;
mainTable.contentInset = UIEdgeInsetsMake(200, 0, 0, 0);
mainTable.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:mainTable];

//添加监听,动态观察tableview的contentOffset的改变
[mainTable addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];

tableData = @[@"12",@"werd",@"sdfgd",@"fs"];

headerView = [[MyView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
headerView.backgroundColor =[UIColor redColor];
[self.view addSubview:headerView];

实现KVC回调方法

#pragma mark KVC 回调
//本例设置headerView的最大高度为200,最小为64
(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"contentOffset"])
{
    CGPoint offset = [change[NSKeyValueChangeNewKey] CGPointValue];
    if (offset.y <= 0 && -offset.y >= 64) {
        
        CGRect newFrame = CGRectMake(0, 0, self.view.frame.size.width, -offset.y);
        headerView.frame = newFrame;
        if (-offset.y <=200)
        {
            mainTable.contentInset = UIEdgeInsetsMake(-offset.y, 0, 0, 0);
        }
    } else {
        CGRect newFrame = CGRectMake(0, 0, self.view.frame.size.width, 64);
        headerView.frame = newFrame;
        mainTable.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    }
}
}

tip

值得注意的是,headerView继承自MyView,如果不继承MyView的话,当滑动headerView的时候,tableView不会移动,因为headerView覆盖在tableVIew上层

MyView继承了UIView,改写了hitTest方法,代码如下:

#import "MyView.h"
 @implementation MyView


//hitTest的作用:当在一个view上添加一个屏蔽罩,但又不影响对下面   view的操作,也就是可以透过屏蔽罩对下面的view进行操作,这个函数就很好用了。
hitTest的用法:将下面的函数添加到UIView的子类中,也就是屏蔽罩类中即可。


(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *result = [super hitTest:point withEvent:event];
if (result == self) {
    return nil;
} else {
    return result;
}
}

@end

至此,完成悬浮tableHeaderView,特此记录,与君共勉。

Tip

学习的路上总是曲折的,每个人都是从菜鸟过来的,遇到问题总是希望能够与他人沟通交流,而在各种群里问了问题就石沉大海,所以想建一个技术交流为主的群,遇到的问题可以记录下来分享给他人,方便了自己,也造就了他人,不管怎样,记录点滴,但愿与君共勉

*QQ群号:527377492 *

《巧妙实现悬浮tableviewHeaderView方法》 Paste_Image.png

点赞