IOS代码布局(五) UICollectionView

(一)初始化

  1、创建一个layout布局类

    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];

     2、设置布局方向为垂直流布局

    layout.scrollDirection = UICollectionViewScrollDirectionVertical;

  3、设置每个item的大小为100*100

    layout.itemSize = CGSizeMake(100, 100);

  4、创建collectionView 通过一个布局策略layout来创建

    UICollectionView * collect = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];

  5、代理设置

    collect.delegate=self;
    collect.dataSource=self;

      6、注册item类型 这里使用系统的类型

    [collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];

  7、设置白色背景颜色

   collect.backgroundColor = [UIColor whiteColor];

  8、加入视窗

    [self.view addSubview:collect];

(二)方法

  1、返回分区个数

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

  2、返回每个分区item个数

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

  3、设定cell间上下间距为2

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 2;
}

  4、设定cell间左右间距为2

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 2;
}

  5、返回item(设定样式)

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];

    //设置图片
    NSURL *imageUrl = [NSURL URLWithString:[[_output objectAtIndex:indexPath.row] objectForKey:@"pic"]];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
    UIImageView *orderImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, cell.frame.size.width,cell.frame.size.height)];
    orderImage.image = image;
    [cell addSubview:orderImage];
    
    //设置名称
    UILabel *name=[[UILabel alloc]initWithFrame:CGRectMake(0, cell.frame.size.height-25, 140, 20)];
    name.text =[[_output objectAtIndex:indexPath.row] objectForKey:@"username"];
    name.textColor = [UIColor whiteColor];
    name.font = [UIFont fontWithName:@"Helvetica" size:10];
    [cell addSubview:name];
   
    
    return cell;
}

 

posted @ 2016-10-10 14:27  贾辰  阅读(389)  评论(0编辑  收藏  举报