//
// 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的用法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.