iOS 类似于礼物说分类栏TableView,CollectionView联动的实现

最近看了各大公司的App上都有左边滑动关联右边跟着一起移动的页面,所以这两天也闲下来了,尝试了一下写了个Demo。写的有点乱,还是希望各位多多见谅,如果有错误或者而优化的地方可以跟我联系 e-mail:chuxiang_work@163.com 希望大家一起进步

这里是个继承于UIView的类,也就是主页面,在Vc里如果要使用的话直接引头文件调用

//
//  LianDongView.m
//  TryFiles
//
//  Created by ChuXiang on 16/1/8.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "LianDongView.h"
#import "LeftTableViewCell.h"
#import "UIView+UIViewAdditions.h"
#import "RightCollectionViewCell.h"
#import "CXNetWorkTool.h"

//限制左边tableView和右边collectionView滑动不会冲突,只保证走一种方法
static BOOL isGetWhatWay = YES;
@interface LianDongView () <UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource>
//tableView选中时底部会有一根红线,其实就是个UIView
@property (nonatomic, strong) UIView *bottomView;
//左边的tableView
@property (nonatomic, strong) UITableView *tab;
//记录上次点击的是哪个cell的IndexPath
@property (nonatomic, strong) NSIndexPath *oldIndexpath;
//右边的collection
@property (nonatomic, strong) UICollectionView *collect;
//记录目前选中的cell的IndexPath
@property (nonatomic, strong) NSIndexPath *recordIndex;


//左边tableView的数据数组
@property (nonatomic, strong) NSArray *leftData;
@end

@implementation LianDongView

- (void)dealloc {
//因为使用了夜间模式,所以写了个通知,这里是给它dealloc
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {

        self.data = [NSMutableArray arrayWithCapacity:0];

        self.oldIndexpath = [NSIndexPath indexPathForRow:0 inSection:0] ;
        self.recordIndex = [NSIndexPath indexPathForRow:0 inSection:0];

        self.tab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.width / 5, self.height) style:UITableViewStylePlain];
        self.tab.delegate = self;
        self.tab.dataSource = self;
        self.tab.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tab.showsVerticalScrollIndicator = NO;
        [self.tab registerClass:[LeftTableViewCell class] forCellReuseIdentifier:@"LeftTableViewCellIdentifier"];
        [self addSubview:self.tab];

        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tab.width / 17, 44)];
        _bottomView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:38 / 255.0 blue:56 / 255.0 alpha:1.0];
        [self.tab addSubview:_bottomView];


        UICollectionViewFlowLayout *flowLaout = [[UICollectionViewFlowLayout alloc] init];
        flowLaout.scrollDirection = UICollectionViewScrollDirectionVertical;
        //    item的大小
        flowLaout.itemSize = CGSizeMake((self.width - self.tab.width - 10) / 3 , 120);
        //    item的最小行间距
        flowLaout.minimumLineSpacing = 5;
        //    item的最小列间距
        flowLaout.minimumInteritemSpacing = 5;

        self.collect = [[UICollectionView alloc] initWithFrame:CGRectMake(self.width / 5, 20, self.width / 5 * 4, self.height) collectionViewLayout:flowLaout];
        [self.collect registerClass:[RightCollectionViewCell class] forCellWithReuseIdentifier:@"RightCollectionViewCellIdentifier"];
        [self.collect registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView1"];
        self.collect.backgroundColor = [UIColor whiteColor];
        self.collect.decelerationRate = 5.0;
        self.collect.delegate = self;
        self.collect.dataSource = self;
        [self addSubview:self.collect];

        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(changeDays:) name:@"Color" object:nil];


    }
    return self;
}

//这里需要从外面传个整个数据数组进来,大家别忘记在.h里写个数组属性,外面好传值进来
-(void)setData:(NSMutableArray *)data {
    if (_data != data) {
        _data = data;
        [self.tab reloadData];
        [self.collect reloadData];
    }
    //    夜间模式换cell得背景颜色
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
        self.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
    }else{
        self.backgroundColor =  [UIColor whiteColor];
    }
}

#pragma mark - Collection
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    self.leftData = [self.data[section] subcategorie];
    return self.leftData.count;
}

- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.data.count;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    self.leftData = [self.data[indexPath.section] subcategorie];

    RightCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"RightCollectionViewCellIdentifier" forIndexPath:indexPath];
    item.model = self.leftData[indexPath.item];
    return item;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {

        if (kind == UICollectionElementKindSectionHeader) {
            UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView1" forIndexPath:indexPath];

            [reusableView removeAllSubviews];
            UILabel *label = [UILabel new];
            label.frame = CGRectMake(0, 20, self.width / 5 * 4, 30);
            [label setFont:[UIFont fontWithName:@"FZLanTingHei-EL-GBK" size:11]];
            label.textAlignment = NSTextAlignmentCenter;
            CXOUtModel *model = self.data[indexPath.section];
            NSString *str = [NSString stringWithFormat:@"————————— %@ —————————", model.name];
            label.textColor = [UIColor grayColor];
            label.text = str;
            [reusableView addSubview:label];
            return reusableView;
        }else{
            UICollectionReusableView *resableviewtow = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath ];
            return resableviewtow;
    }
}

// 头视图高度
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return  CGSizeMake(self.width / 5 * 4, 70);
}



// collectionView的头视图出现的时候tableView切换
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return;
    }
    if (isGetWhatWay == YES) {
        self.recordIndex = [NSIndexPath indexPathForRow:self.recordIndex.section - 1 inSection:self.recordIndex.row];

        //    夜间模式换cell得背景颜色
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
            LeftTableViewCell *cell1 = [self.tab cellForRowAtIndexPath:self.recordIndex];
            cell1.label.textColor = [UIColor whiteColor];

            LeftTableViewCell *cell2 = [self.tab cellForRowAtIndexPath:self.oldIndexpath];
            cell2.label.textColor = [UIColor whiteColor];

        }else{
            LeftTableViewCell *cell1 = [self.tab cellForRowAtIndexPath:self.recordIndex];
            cell1.label.textColor = [UIColor blackColor];

            LeftTableViewCell *cell2 = [self.tab cellForRowAtIndexPath:self.oldIndexpath];
            cell2.label.textColor = [UIColor blackColor];
        }


        NSIndexPath *path = [NSIndexPath indexPathForRow:indexPath.section - 1 inSection:indexPath.row];

        LeftTableViewCell *cell = [self.tab cellForRowAtIndexPath:path];
        cell.label.textColor = [UIColor colorWithRed:255 / 255.0 green:38 / 255.0 blue:56 / 255.0 alpha:1.0];

        self.bottomView.frame = CGRectMake(0, 44 * path.row, self.tab.width / 17, 44);


        NSInteger section = indexPath.section;
        NSIndexPath *tabIndexPath = [NSIndexPath indexPathForRow:section - 1 inSection:0];
        [self.tab selectRowAtIndexPath:tabIndexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];

        self.recordIndex = indexPath;

    }


}

#pragma mark - CollectionView Click
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.leftData = [self.data[indexPath.section] subcategorie];
    NSMutableArray *setArray = [NSMutableArray arrayWithCapacity:0];
    CXGiftModel *model = self.leftData[indexPath.item];
    NSString *urlStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/item_subcategories/%@/items?limit=20&offset=0", model.NewId];
    [setArray addObject:urlStr];
    [setArray addObject:model.name];
    _myBlock(setArray);
}

#pragma mark - TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    LeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LeftTableViewCellIdentifier"];
    //    夜间模式换cell得背景颜色
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
       cell.label.textColor = [UIColor whiteColor];

    }else{
       cell.label.textColor = [UIColor blackColor];
    }


    UIView *back = [[UIView alloc] initWithFrame:cell.frame];
    back.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = back;
    cell.model = self.data[indexPath.row];

    return cell;
}

//点击左边的cell让右边的collectionView item跟着滑动到指定的偏移量
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {



        [tableView deselectRowAtIndexPath:indexPath animated:YES];

        LeftTableViewCell *cell2 = [tableView cellForRowAtIndexPath:self.recordIndex];

        LeftTableViewCell *cell1 = [tableView cellForRowAtIndexPath:self.oldIndexpath];

    //    夜间模式换cell得背景颜色
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
            cell1.label.textColor = [UIColor blackColor];
            cell2.label.textColor = [UIColor blackColor];

        }else{
            cell1.label.textColor = [UIColor whiteColor];
            cell2.label.textColor = [UIColor whiteColor];
        }

        LeftTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.label.textColor = [UIColor colorWithRed:255 / 255.0 green:38 / 255.0 blue:56 / 255.0 alpha:1.0];


        self.bottomView.frame = CGRectMake(0, 44 * indexPath.row, self.tab.width / 17, 44);




        NSInteger section = indexPath.row + 1;
        NSIndexPath *tabIndexPath = [NSIndexPath indexPathForRow:0 inSection:section];

        [self.collect scrollToItemAtIndexPath:tabIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];




        self.oldIndexpath = indexPath;

         isGetWhatWay = YES;


}

下面是tableView的自定义cell代码,这里就是最简单的部分,大家根据自己项目和公司App的要求在这里更改左边标签的样式,其实看了好多App也基本大同小异都是类似于这种

//
//  LeftTableViewCell.m
//  TryFiles
//
//  Created by ChuXiang on 16/1/8.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "LeftTableViewCell.h"
#import "UIView+UIViewAdditions.h"
//static BOOL changeColor = YES;
@interface LeftTableViewCell ()

@end
@implementation LeftTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        self.label = [UILabel new];
        self.label.textAlignment = NSTextAlignmentCenter;
        [self.label setFont:[UIFont fontWithName:@"FZLanTingHei-EL-GBK" size:13]];
        [self addSubview:self.label];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.label.frame = CGRectMake(0, 0, self.width, self.height);
}

- (void)setModel:(CXOUtModel *)model {
    if (_model != model) {
        _model = model;
        }
    self.label.text = model.name;
    //    夜间模式换cell得背景颜色
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
        self.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
        self.label.textColor = [UIColor whiteColor];

    }else{
        self.backgroundColor =  [UIColor whiteColor];
        self.label.textColor = [UIColor blackColor];
    }

}

CollectionView item的自定义 如上面tableView一样

//
//  RightCollectionViewCell.m
//  TryFiles
//
//  Created by ChuXiang on 16/1/8.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "RightCollectionViewCell.h"
@interface RightCollectionViewCell ()
@property (nonatomic, strong) UIImageView *image;
@property (nonatomic, strong) UILabel *textLabel;
@end
@implementation RightCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.image = [UIImageView new];
        [self addSubview:self.image];

        self.textLabel = [UILabel new];
        self.textLabel.textAlignment = NSTextAlignmentCenter;
        [self.textLabel setFont:[UIFont fontWithName:@"FZLanTingHei-EL-GBK" size:12]];
        [self addSubview:self.textLabel];

    }
    return self;
}

- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    [super applyLayoutAttributes:layoutAttributes];
    self.image.frame = CGRectMake(0, 0, self.width, self.height - 15);
    self.textLabel.frame = CGRectMake(0, self.image.bottom, self.width, 15);

}



- (void)setModel:(CXGiftModel *)model {
    if (_model != model) {
        _model = model;
    }
    self.textLabel.text = model.name;
    [self.image sd_setImageWithURL:[NSURL URLWithString:model.icon_url]];


}

这样就基本实现了,对了,我是直接用AFNetworking请求的数据,装到了Model里,所以我每个cell里都传了个model进去。大家如果用的别的方法传的数据,把那里改了就行。
其实这个东西还是挺简单的,主要就是tableView跟collectionView关联那块有稍微一点点的麻烦,大家多看看就能懂。
请大家多给我找点BUG和代码优化的地方,多跟我交流。这样才能成长

e-mail:chuxiang_work@163.com

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值