//
// ViewController.m
// UI1_UICollectionView
//
// Created by Fan_JinXin on 15/7/16.
// Copyright (c) 2015年 Fan_Jinxin. All rights reserved.
//
#import "ViewController.h"
//重用标志符
#define kCellReuseId @"cellId"
@interface ViewController () <UICollectionViewDataSource,UICollectionViewDelegate>
{
UICollectionView *_collectionView;
NSMutableArray *_dataList;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//1.创建数据源
[self createDataList];
//2.创建UI
[self createCollectionView];
//3.遵守协议,设置代理
}
//创建数据源
- (void)createDataList
{
_dataList = [NSMutableArray array];
for (int i=0; i<20; i++) {
NSString *str = [NSString stringWithFormat:@"第%d个网格", i+1];
[_dataList addObject:str];
}
}
//创建UI
- (void)createCollectionView
{
//第一个参数: collectionView 的位置
//第二个参数: 布局对象, UICollectionViewLayout类(子类)的对象
//规则布局
//UICollectionViewFlowLayout:UICollectionViewLayout
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//上下左右边界的距离top, left, bottom, right
layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
//设置cell的大小
layout.itemSize = CGSizeMake(180, 100);
//设置横向的最小距离
layout.minimumInteritemSpacing = 5;
//设置竖向的最小距离
layout.minimumLineSpacing = 10;
_collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
//设置代理
_collectionView.delegate = self;
_collectionView.dataSource = self;
//注册cell
//第一个参数:cell的类型
//第二个参数:cell的重用标识符
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:kCellReuseId];
_collectionView.backgroundColor = [UIColor cyanColor];
[self.view addSubview:_collectionView];
}
#pragma mark ---collectionView代理---
//返回分区的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
//返回每个分区有多少个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _dataList.count;
}
//返回cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//UITableView : indexPath --> section row
//UICollectionView: indexPath --> section item
//从重用队列中取出cell
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellReuseId forIndexPath:indexPath];
cell.backgroundColor = [UIColor yellowColor];
//移除cell.contentView 的子视图
for (UIView *view in cell.contentView.subviews) {
[view removeFromSuperview];
}
//在cell上显示内容
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 180, 40)];
label.text = _dataList[indexPath.item];
label.textAlignment = NSTextAlignmentCenter;
[cell.contentView addSubview:label];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
iOS求生之路(四)UICollectionView的用法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.