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

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

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


不要被这张乱七八糟的层级关系吓住,其实原理很简单:就是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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章