iOS UITableView头部悬停+UITableView侧滑嵌套

ok,好久没有写文章了,最近真的太忙了(这借口好棒!)。今天准备给大家分享一个非常常见的小功能,UITableView是大家最常用的控件,在使用的过程中会遇到各种各样的封装和嵌套使用,先给大家看一张图片:
tableViewList.gif

大家在平时的开发工程中肯定随处可见这项功能,虽然实现很简单,但是层级关系大家还是要理解一下:


UITableView层级关系.jpeg

不要被这张乱七八糟的层级关系吓住,其实原理很简单:就是UITableView-->UICollectionView-->UIViewController-->UITableView。在主控制器上的tableViewCell中,放入横向滑动的UICollectionView,再在UICollectionViewCell中加入子控制器的视图,在子控制器中添加UITableView。

层级关系搞明白后,大家先不要着急实现,其实最重要的一步,就是打开主控制器和子控制器的UITableView手势联动。先上主控制器中UITableView的代码:

#import "LYFTableView.h"
#import "ViewController.h"
#import "LYFCollectionView.h"
#import "LYFTableViewHeaderView.h"

#define kScreenWidth  [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight [[UIScreen mainScreen] bounds].size.height

@interface LYFTableView() <UITableViewDelegate, UITableViewDataSource>

/// 横向的滚动视图
@property (nonatomic, strong) LYFCollectionView *collectionView;

@end

static NSString *tableViewCell = @"UITableViewCell";
static NSString *tableViewHeaderView = @"LYFTableViewHeaderView";

@implementation LYFTableView

-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    if (self = [super initWithFrame:frame style:style]) {
        [self setupTableView];
    }
    
    return self;
}

#pragma mark - 允许接受多个手势 (这个方法很重要,不要遗漏)
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

#pragma mark - 设置列表
-(void)setupTableView {
    self.delegate = self;
    self.dataSource = self;
    /// 64.f 是导航控制器的高度    50.f是列表的section头的高度
    self.rowHeight = kScreenHeight - 64.f - 50.f;
    
    /// 设置tableView的表头
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 300)];
    headerView.backgroundColor = [UIColor yellowColor];
    /// 0.5是因为刺眼😂
    headerView.alpha = 0.5;
    self.tableHeaderView = headerView;
    
    [self registerClass:[LYFTableViewHeaderView class] forHeaderFooterViewReuseIdentifier:tableViewHeaderView];
    
    __weak typeof(self) weakSelf = self;
    self.collectionView.scrollAction = ^(CGFloat proportion) {
        LYFTableViewHeaderView *header = (LYFTableViewHeaderView *)[weakSelf headerViewForSection:0];
        /// 改变section头部按钮的大小和颜色
        if (header) {
            header.proportion = proportion;
        }
    };
}

#pragma mark - Set方法
-(void)setViewController:(ViewController *)viewController {
    _viewController = viewController;
    
    self.collectionView.viewController = viewController;
}

#pragma mark - UITableViewDelegate / UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableViewCell];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableViewCell];
        
        /// 在tableViewCell中添加控制器
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.contentView addSubview:self.collectionView];
    }
    
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    LYFTableViewHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:tableViewHeaderView];
    
    header.clickAction = ^(NSInteger index) {
        switch (index) {
            case 1: {
                [self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
                break;
            }
            default: {
                [self.collectionView setContentOffset:CGPointMake(kScreenWidth, 0) animated:YES];
                break;
            }
        }
    };
    
    return header;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50.f;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.scrollAction) {
        self.scrollAction();
    }
}

#pragma mark - Get方法
-(LYFCollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(kScreenWidth, kScreenHeight - 64.f - 50.f);
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.sectionInset = UIEdgeInsetsZero;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        /// 64.f 是导航控制器的高度    50.f是列表的section头的高度
        _collectionView = [[LYFCollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 50.f) collectionViewLayout:flowLayout];
    }
    
    return _collectionView;
}

大家可以看到

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer;

就是打开主控制器UITableView手势联动的方法。

然后在联动的过程中,始终保持主控制器的UITableView和子控制器的UITableView只有一个可以滑动。这个就需要一个开关去控制,我在方法里面使用的是一个BOOL参数:isCanScroll。
主控制器的代码:

#import "ViewController.h"
#import "LYFTableView.h"
#import "LYFViewController.h"

#define kScreenWidth  [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight [[UIScreen mainScreen] bounds].size.height

@interface ViewController ()

/// 列表(主列表,只有一个cell,用于装UICollectionView)
@property (nonatomic, strong) LYFTableView *tableView;
/// 是否可以滑动
@property (nonatomic, assign) BOOL isCanScroll;
/// 第一个控制器
@property (nonatomic, strong) LYFViewController *lyfVCOne;
/// 第二个控制器
@property (nonatomic, strong) LYFViewController *lyfVCTwo;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"列表";
    
    self.isCanScroll = YES;
    
    [self addChildViewController:self.lyfVCOne];
    [self addChildViewController:self.lyfVCTwo];
    
    __weak typeof(self) weakSelf = self;
    self.lyfVCOne.noScrollAction = ^{
        weakSelf.isCanScroll = YES;
        weakSelf.lyfVCTwo.isCanScroll = NO;
        weakSelf.lyfVCTwo.tableView.contentOffset = CGPointZero;
    };
    
    self.lyfVCTwo.noScrollAction = ^{
        weakSelf.isCanScroll = YES;
        weakSelf.lyfVCOne.isCanScroll = NO;
        weakSelf.lyfVCOne.tableView.contentOffset = CGPointZero;
    };
    
    self.tableView.scrollAction = ^{
        CGFloat scrollY = [weakSelf.tableView rectForSection:0].origin.y;
        if (weakSelf.tableView.contentOffset.y >= scrollY) {
            if (weakSelf.isCanScroll == YES) {
                weakSelf.isCanScroll = NO;
                
                weakSelf.lyfVCOne.isCanScroll = YES;
                weakSelf.lyfVCOne.tableView.contentOffset = CGPointZero;
                weakSelf.lyfVCTwo.isCanScroll = YES;
                weakSelf.lyfVCTwo.tableView.contentOffset = CGPointZero;
            }
            
            weakSelf.tableView.contentOffset = CGPointMake(0, scrollY);
        }else{
            if (weakSelf.isCanScroll == NO) {
                weakSelf.tableView.contentOffset = CGPointMake(0, scrollY);
            }
        }
    };
    
    [self.view addSubview:self.tableView];
}

#pragma mark - Get方法
-(LYFTableView *)tableView {
    if (!_tableView) {
        _tableView = [[LYFTableView alloc] initWithFrame:CGRectMake(0, 64.f, kScreenWidth, kScreenHeight - 64.f) style:UITableViewStylePlain];
        /// 把控制器传给tableView,这样逻辑就在view中,viewController显得整齐(个人习惯)
        _tableView.viewController = self;
    }
    
    return _tableView;
}

-(LYFViewController *)lyfVCOne {
    if (!_lyfVCOne) {
        _lyfVCOne = [[LYFViewController alloc] init];
    }
    
    return _lyfVCOne;
}

-(LYFViewController *)lyfVCTwo {
    if (!_lyfVCTwo) {
        _lyfVCTwo = [[LYFViewController alloc] init];
    }
    
    return _lyfVCTwo;
}

@end

子控制器的代码:

#import "LYFViewController.h"

#define kScreenWidth  [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight [[UIScreen mainScreen] bounds].size.height

#define random(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)/255.0]
/// 随机色
#define randomColor random(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256))

@interface LYFViewController () <UITableViewDataSource, UITableViewDelegate>

@end

static NSString *tableViewCell = @"UITableViewCell";

@implementation LYFViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
}

#pragma mark - UITableViewDataSource / UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 50.f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableViewCell];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableViewCell];
        cell.contentView.backgroundColor = randomColor;
    }
    
    cell.textLabel.text = [NSString stringWithFormat:@"这里是%ld行", indexPath.row];
    
    return cell;
}

#pragma mark - 滑动方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (!self.isCanScroll) {
        scrollView.contentOffset = CGPointZero;
    }
    
    /// 当偏移量小于0时,不能滑动,并且使主要视图的UITableView滑动
    if (scrollView.contentOffset.y < 0 ) {
        self.isCanScroll = NO;
        scrollView.contentOffset = CGPointZero;
        if (self.noScrollAction) {
            self.noScrollAction();
        }
    }
}

#pragma mark - Get方法
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64.f - 50.f) style:UITableViewStylePlain];
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        _tableView.rowHeight = 40.f;
    }
    
    return _tableView;
}

@end

很明显,在三个控制器中(一个主控制器和两个子控制器),它们的UITableView始终在联动,相互控制。当滑动大于表头的高度时,子控制器滑动,否则主控制器滑动。原理实际上是很简单的。

至于section头部视图的两个按钮颜色变化,完全是由UICollectionView的偏移量来改变的。具体的代码很简单,我就不在文章中详细描述了。

总体来看,实现内容其实并不难,主要是想法需要打通。喜欢的同学们点个赞啦😍。
最后附上Gitbug链接:https://github.com/Fdevelopmenter/UITableViewNesting

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,937评论 3 118
  • 一大早到办公室,先急着去安排好昨天客人交待的事,省的等会儿司机来了让人家崔,被人崔感觉一点也不好,喜欢自己提早安排...
    浪迹天涯周zoe阅读 182评论 2 2
  • 叶子和帆船是朋友介绍的认识的,高中同学,但互不认识。 两人聊着聊着帆船说他想见叶子,于是搭车毫无防备的跑到叶子学校...
    箱猫日和阅读 203评论 1 0
  • 2018年7月6日 星期五 天气晴 今天上午孩子上完学就放暑假了,这近两个月的假期,我们要安排好,既要让孩...
    秋日私语666阅读 229评论 0 0