美文网首页
02MVVM实现CollectionView展示数据

02MVVM实现CollectionView展示数据

作者: myk | 来源:发表于2018-05-16 17:33 被阅读18次
在展示表格数据的时候,因为要实现协议方法,会造成VC里面看起来代码很多,显得很臃肿,这个时候我们可以通过MVVM实现VC的瘦身。
  • 在VC里面要实现CollectionView的初始化,数据的获取
-(UICollectionView *)collView{
   if (!_collView) {
       self.layout = [[UICollectionViewFlowLayout alloc] init];
       self.layout.itemSize = CGSizeMake(80, 100);
       CGRect collFrame = self.view.frame;
       collFrame.size.height = collFrame.size.height - 104;
       _collView = [[UICollectionView alloc] initWithFrame:collFrame collectionViewLayout:self.layout];
       _collView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.2];
   }
   return _collView;
}
-(void)loadData{
   //创建信号量,保证数组有数据之后才初始化VM
   dispatch_semaphore_t semap = dispatch_semaphore_create(0);
   typeof(self)weakself = self;
   NSURLSession *session = [NSURLSession sharedSession];
   NSURL *url = [NSURL URLWithString:@""];
   NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       if (error) {
           NSLog(@"error === %@",error);
           return;
       }
       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       NSDictionary *dictData = dict[@"data"];
       NSArray *arr = dictData[@"templist"];
       for (NSDictionary *dictList in arr) {
           [weakself.arrData addObject:dictList];
       }
       dispatch_async(dispatch_get_main_queue(), ^{
           [self.collView.mj_header endRefreshing];
           [self.collView.mj_footer endRefreshing];
       });
       dispatch_semaphore_signal(semap);
   }];
   [dataTask resume];
   dispatch_semaphore_wait(semap, DISPATCH_TIME_FOREVER);
   self.viewModel = [ThirdViewModel collView:self.collView withData:self.arrData flowlayout:self.layout selected:^(NSIndexPath *cell) {
       NSLog(@"indexpath ==== %@",cell);
   }];
   //UICollectionView的代理设置为VM
   self.collView.delegate = self.viewModel;
   self.collView.dataSource = self.viewModel;
}
  • VM里面遵循协议,同时对外暴露初始化方法
.h文件
#import <Foundation/Foundation.h>
typedef void(^selectCell)(NSIndexPath *cell);

@interface ThirdViewModel : NSObject<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, copy) selectCell selectedCell;//点击cell
@property (nonatomic, copy) NSArray *arr;
@property (nonatomic) UICollectionView *coll;
@property (nonatomic) UICollectionViewFlowLayout *layout;
//初始化方法,同时获取到数据
+(instancetype)collView:(UICollectionView *)collView withData:(NSArray *)dataList flowlayout:(UICollectionViewFlowLayout *)layout selected:(selectCell)selected;
@end
  • 在.m文件中初始化的实现
+(instancetype)collView:(UICollectionView *)collView withData:(NSArray *)dataList flowlayout:(UICollectionViewFlowLayout *)layout selected:(selectCell)selected{
    return [[[self class] alloc] initCollView:collView withData:dataList flowlayout:layout selected:selected];
}

-(instancetype)initCollView:(UICollectionView *)collView withData:(NSArray *)dataList flowlayout:(UICollectionViewFlowLayout *)layout selected:(selectCell)selected{
    if (self = [super init]) {
        self.selectedCell = selected;
        self.arr = dataList;
        self.coll = collView;
        self.layout = layout;
        [self.coll registerClass:[ThirdCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        [self.coll registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"collfooter"];
        [self.coll registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collheader"];
    }
    return self;
}
  • 在.m中还要实现CollectionView的协议方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.arr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ThirdCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    NSDictionary *dict = self.arr[indexPath.row];
    cell.lbl.text = [NSString stringWithFormat:@"%@", dict[@"pttypename"]];
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.selectedCell(indexPath);
}

#pragma mark --- Header的size
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeZero;
    }else{
        return CGSizeMake(KScreenWidth, 30);
    }
}
#pragma mark --- Footer的size
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(KScreenWidth, 30);
}
//collectionView的header和footer
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"collfooter" forIndexPath:indexPath];
        footerView.backgroundColor = [UIColor orangeColor];
        return footerView;
    }else{
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collheader" forIndexPath:indexPath];
        header.backgroundColor = [UIColor redColor];
        return header;
    }
}
//设置collectionView的一个section的偏移量,可以修改cell距离边框和cell距离SectionFooter和SectionHeader的距离
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(8, 8, 8, 8);
}

刚刚接触MVVM,接下来要去学习Reactcocoa。菜鸟一个,如果有什么说的不对的地方,希望大家指出来,小弟在此谢过了。

相关文章

网友评论

      本文标题:02MVVM实现CollectionView展示数据

      本文链接:https://www.haomeiwen.com/subject/wofmdftx.html