效果圖如下:
要想實現上述效果,需要先有一個繼承於NSObject的Model類(這裡起名叫DestinationModel)用來賦值,需要一個繼承於UICollectionViewCell的類(DestinCollectionViewCell)用來自定義cell,還需要一個繼承於UIView的類(DestinationView)用來顯示資料,還需要一個繼承於UIViewController的類(DestinationViewController),最後需要一個繼承於UICollectionReusableView的類(DestinCollectionReusableView)用於顯示標題
Model類中的寫法
DestinationModel.h
#import <Foundation/Foundation.h>
@interface DestinationModel : NSObject
///接收圖片
@property(nonatomic,strong)NSString *cover;
///接收城市名
@property(nonatomic,strong)NSString *name;
@end
DestinationModel.m
#import "DestinationModel.h"
@implementation DestinationModel
//防止崩潰
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
}
@end
DestinationView中的寫法
DestinationView.h
#import <UIKit/UIKit.h>
@interface DestinationView : UIView
@property (nonatomic,strong)UICollectionView *destinView;
@end
DestinationView.m
#import "DestinationView.h"
@implementation DestinationView
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self addAllViews];
}
return self;
}
- (void)addAllViews{
UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc]init];
// 每個item 的大小
flowLayout.itemSize = CGSizeMake(self.frame.size.width / 2 - 17 ,self.frame.size.height *0.25);
//每個item的距離
flowLayout.sectionInset=UIEdgeInsetsMake(10, 10, 10, 10);
//豎屏滑動
flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;
self.destinView=[[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:flowLayout];
self.destinView.backgroundColor = [UIColor whiteColor];
[self addSubview:self.destinView];
}
@end
DestinCollectionViewCell
DestinCollectionViewCell.h
#import <UIKit/UIKit.h>
@interface DestinCollectionViewCell : UICollectionViewCell
///圖片
@property (nonatomic,strong) UIImageView *imageView;
///item所在的indexpath
@property (nonatomic,strong) UILabel *itemLabel;
@end
DestinCollectionViewCell.m
#import "DestinCollectionViewCell.h"
@implementation DestinCollectionViewCell
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
[self addSubview:self.imageView];
self.itemLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.frame.size.height-45, self.frame.size.width,self.frame.size.height*0.28)];
self.itemLabel.textAlignment = NSTextAlignmentCenter;
self.itemLabel.textColor = [UIColor whiteColor];
[self.imageView addSubview:self.itemLabel];
}
return self;
}
@end
DestinationViewController
DestinationViewController.h
#import <UIKit/UIKit.h>
@class DestinCollectionViewCell;
#import "DestinationView.h"
@interface DestinationViewController : UIViewController
@property(nonatomic,strong)DestinCollectionViewCell *collection;
@property(nonatomic,strong)DestinationView *desrinV;
@end
DestinationViewController.m
//
// DestinationViewController.m
// travel1.0
//
// Created by lanou3g on 16/3/25.
// Copyright © 2016年 浮誇. All rights reserved.
//
#import "DestinationViewController.h"
#import "DestinCollectionViewCell.h"
#import "DestinationModel.h"
#import "DestinCollectionReusableView.h"
@interface DestinationViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
///接收title
@property (nonatomic,strong)NSMutableArray *keyArray;
///接收所有資料
@property (nonatomic,strong)NSMutableDictionary *allDict;
@end
@implementation DestinationViewController
//懶載入
- (NSMutableArray *)keyArray
{
if (_keyArray ==nil) {
_keyArray = [NSMutableArray new];
}
return _keyArray;
}
//懶載入
- (NSMutableDictionary *)allDict
{
if (_allDict == nil) {
_allDict = [NSMutableDictionary new];
}
return _allDict;
}
- (void)loadView{
self.desrinV = [[DestinationView alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.view = self.desrinV;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setDelegate];
[self setData];
[self setViews];
}
- (void)setDelegate
{
self.desrinV.destinView.delegate = self;
self.desrinV.destinView.dataSource = self;
}
- (void)setData
{
NSURL *url = [NSURL URLWithString:@"http://api.breadtrip.com/destination/v3/"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *mainArray = dict[@"elements"];
for (NSDictionary *dict1 in mainArray) {
NSString *key = dict1[@"title"];//
[self.keyArray addObject:key]; //
NSArray *secArray = dict1[@"data"];
NSMutableArray *tempArray = [NSMutableArray new]; //
for (NSDictionary *dict2 in secArray) {
DestinationModel *model = [[DestinationModel alloc] init];
[model setValuesForKeysWithDictionary:dict2];
[tempArray addObject: model];
}
[self.allDict setObject:tempArray forKey:key];//
}
//回到主執行緒
[self performSelectorOnMainThread:@selector(mian) withObject:self waitUntilDone:YES];
}];
[task resume];
}
- (void)mian{
//重新整理列表
[self.desrinV.destinView reloadData];
}
- (void)setViews
{
//註冊cell
[self.desrinV.destinView registerClass:[DestinCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
//註冊header
[self.desrinV.destinView registerClass:[DestinCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"cell_id"];
}
//實現代理方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return self.keyArray.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
NSString *key = self.keyArray[section];
return [self.allDict[key] count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
DestinCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
NSString *key = self.keyArray[indexPath.section];
DestinationModel *model = self.allDict[key][indexPath.row];
cell.itemLabel.text = model.name;
cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.cover]]];
return cell;
}
//實現dataSource代理方法
//collection大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
return CGSizeMake(self.desrinV.destinView.bounds.size.width, 30);
}
//header
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
DestinCollectionReusableView *headerView =[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"cell_id" forIndexPath:indexPath];
headerView.titleLabel.text = self.keyArray[indexPath.section];
return headerView;
}
@end