ios UICollectionView用法

1,UICollectionView只能在6.0以上版本使用;

2,在代码中初始化一个UICollectionView:

UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc] init];
    
    self.girdView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_SIZE.width, SCREEN_SIZE.height-64) collectionViewLayout:flowLayout];
    self.girdView.backgroundColor = [UIColor lightGrayColor];
    self.girdView.delegate = self;
    self.girdView.dataSource = self;
    [self.view addSubview:self.girdView];

[self.girdViewregisterNib:[UINibnibWithNibName:@"TJMyCell"bundle:nil] forCellWithReuseIdentifier:@"CollectCell"];

3,各种代理:

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 5;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TJMyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectCell" forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor whiteColor];
    //设置label文字
//    cell.lbl.text = [NSString stringWithFormat:@"{%ld,%ld}",(long)indexPath.row,(long)indexPath.section];
    
    return cell;
}

#pragma mark --UICollectionViewDelegateFlowLayout

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
	return CGSizeMake(96, 100);
}

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
	return UIEdgeInsetsMake(5, 5, 5, 5);
}

#pragma mark --UICollectionViewDelegate

//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
	UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
	cell.backgroundColor = [UIColor redColor];
    [UIView animateWithDuration:0.3 animations:^{
        cell.backgroundColor = [UIColor whiteColor];
    }];
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
	return YES;
}

4,自定义UICollectionViewCell, --> “TJMyCell”:

  创建TJMyCell.h,TJMyCell.m,TJMyCell.xib;将TJMyCell.xib的Custom Class设为"TJMyCell";

一切OK;

posted @ 2014-04-18 20:23  天下.无贼  阅读(332)  评论(0)    收藏  举报