如何在集合视图中仅为单行设置两个图像

时间:2016-03-01 16:25:59

标签: ios objective-c uicollectionview

我尝试使用故事板创建带图像的集合视图。我总共有6张图片。所以每行我需要显示2张图片。并且在一行中的两个图像之间不应存在间隙。当我在所有屏幕中打开时,它应该是单行的两个图像。如何在我的代码中添加它:

ViewController.m:

#import "ViewController.h"
#import "CustomCell.h"

@interface ViewController ()

@end

@implementation ViewController {

    NSArray *arrayImages;
    NSArray *arrayLabel;

}
@synthesize MycollectionView;


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [[self MycollectionView]setDataSource:self];
    [[self MycollectionView]setDelegate:self];

    arrayImages =[[NSArray alloc] initWithObjects:@"image1.png",@"image2.png",@"image3.png",@"image4.png",@"image5.png",@"image6.png", nil];
    arrayLabel = [[NSArray alloc] initWithObjects:@"image1",@"image2",@"image3",@"image4",@"image5",@"image6", nil];
}
// datasource and delegate method
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;

}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [arrayImages count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellIdentifier = @"Cell";
    CustomCell *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    [[Cell myimage] setImage:[UIImage imageNamed:[arrayImages objectAtIndex:indexPath.item]]];
    [[Cell myLabel]setText:[arrayLabel objectAtIndex:indexPath.item]];


    return Cell;

}

CustomCell.h

@interface CustomCell : UICollectionViewCell


@property (weak, nonatomic) IBOutlet UIImageView *myimage;


@property (weak, nonatomic) IBOutlet UILabel *myLabel;

@end

1 个答案:

答案 0 :(得分:0)

动态设置集合视图委托方法

   func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width/2, height: collectionView.frame.size.width/2)
}

它创建相等宽度和高度的集合视图单元格,即Square