下图为京东商城的截图


很多人看到这个,第一眼想到的是用TableView和CollectionView来做切换,笔者刚开始也是认为这么做,后来发现还有一个非常的简单方法,就可以实现这个功能。
实现代码
1、首先创建一个CollectionView。
- (UICollectionView *)collectionView
{
if (!_collectionView)
{
UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
//设置滚动方向
[flowlayout setScrollDirection:UICollectionViewScrollDirectionVertical];
//左右间距
flowlayout.minimumInteritemSpacing = 2;
//上下间距
flowlayout.minimumLineSpacing = 2;
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(2 , 2 , self.view.bounds.size.width - 4, self.view.bounds.size.height - 4) collectionViewLayout:flowlayout];
_collectionView.delegate = self;
_collectionView.dataSource = self;
_collectionView.showsVerticalScrollIndicator = NO;
_collectionView.showsHorizontalScrollIndicator = NO;
[_collectionView setBackgroundColor:[UIColor clearColor]];
//注册cell
[_collectionView registerClass:[GridListCollectionViewCell class] forCellWithReuseIdentifier:kCellIdentifier_CollectionViewCell];
}
return _collectionView;
}
然后去京东商城抓取json数据,再去解析数据装入模型,objectWithDictionary:是将字典转化为模型,这个工具是我用 Runtime 写的,一行代码解析数据。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 默认列表视图
_isGrid = NO;
NSString *path = [[NSBundle mainBundle] pathForResource:@"product" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[self.view addSubview:self.collectionView];
NSArray *products = dict[@"wareInfo"];
for (id obj in products) {
[self.dataSource addObject:[GridListModel objectWithDictionary:obj]];
}
}
再去自定义CollectionViewCell,给cell添加一个属性isGrid,用来判断是列表还是格子视图。
.h文件:
#import <UIKit/UIKit.h>
#define kCellIdentifier_CollectionViewCell @"GridListCollectionViewCell"
@class GridListModel;
@interface GridListCollectionViewCell : UICollectionViewCell
/**
0:列表视图,1:格子视图
*/
@property (nonatomic, assign) BOOL isGrid;
@property (nonatomic, strong) GridListModel *model;
@end










