iOS学习9:UICollectionView的简单使用

本文更新 2014-06-27 

效果图

100049_W46M_735123.jpg


storyboard可以快速对collection和table中cell进行布局,这样得好处是你可以直观得看到cell摆放位置布局状态,并可以将复用的Cell直接放在Collection中,如果你要对cell的间距进行调整,可以方便地直接调数据

在画布上添加一个CollectionView,并创建映射,命名为myCollection,单词写错。。算鸟

095917_8jz9_735123.png


cell之间的间距,通过调整Min Spacing,Cell据Collection的上下左右的距离通过调整Section Insets,cell size,header size,footer size意思都很明显了,总之大家自己调调看就知道了,将Items多添加几个看下布局,然后调整间距,得到心中最佳效果,然后将items的数量设置为1。

095917_nnYw_735123.png

本文cell上是一个imageView和一个label,先添加到cell上,设置好坐标,然后新建一个UICollectionViewCell的类,命名为collectionCell,将Storyboard中的Cell的Custom Class设置为collectionCell,为imageView和Label添加映射。分别命名为imageView和titleLabel。在controller的.m文件中

#import "collectionCell.h"

095917_nAGT_735123.png

095918_maVc_735123.png

在viewController中实现DataSource和Delegate, 并定义一个Array用来存放image

@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>

@property (strong, nonatomic)NSMutableArray *dataMArr;// 数据源
@property (weak, nonatomic) IBOutlet UICollectionView *myConllection;// collectionView

@end

在.m中设置数据源,collection代理,并实现dataSource方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setUpCollection];
}

-(void)setUpCollection{
    self.dataMArr = [NSMutableArray array];
    for(NSInteger index = 0;index<9; index++){
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld",(long)index+1]];
        NSString *title = [NSString stringWithFormat:@"{0,%ld}",(long)index+1];
        NSDictionary *dic = @{@"image": image, @"title":title};
        [self.dataMArr addObject:dic];
    }
    self.myConllection.delegate = self;
    self.myConllection.dataSource = self;
    

}
#pragma mark - Collection View Data Source
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataMArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *collectionCellID = @"myCollectionCell";
    collectionCell *cell = (collectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:collectionCellID forIndexPath:indexPath];
    
    NSDictionary *dic    = self.dataMArr[indexPath.row];
    UIImage *image       = dic[@"image"];
    NSString *title      = dic[@"title"];
    
    cell.imageView.image = image;
    cell.titleLabel.text = title;
    
    return cell;
};

在这里下载源码

转载于:https://my.oschina.net/joanfen/blog/160156

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值