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

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