简体   繁体   中英

cell of collection view not displaying in row

I have 12 images and i want to display this images in UICollectionView with 4 rows where each rows have 3 images.

Here is my .h file code

    @interface MyMusic : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
{
UICollectionView *_collectionView;
}
@end

and here is my .m file code

- (void)viewDidLoad{
enter code hereUICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(100, 100)];
[flowLayout setMinimumLineSpacing:5];
[flowLayout setMinimumInteritemSpacing:5];
[flowLayout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];

_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10,238, 300, 200) collectionViewLayout:flowLayout];
_collectionView.backgroundColor = [UIColor redColor];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[self.view addSubview:_collectionView];
}


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

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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
enter  UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

cell.backgroundColor=[UIColor greenColor];
return cell;
}

above code working fine but my output will not come in proper

its looking like this

在此处输入图片说明

any one can help me how can i solve this ?

Your UICollectionView width is 300 points , and your item's width is 100 points . Interitem space is 5 points, so

100*3 + 5*2 = 310. 

That's why you see only 2 columns.

Make your cells' width a little smaller, for example 290

Or set interitem spacing to 0.

Main rule - your UICollecitionView width should be larger or equal to sum of your cells widths + interitem spacing

replace

[flowLayout setItemSize:CGSizeMake(100, 100)];

by

[flowLayout setItemSize:CGSizeMake(75,100 )]; 

I am using 75 just for the trial purpose and consider iphone screen.so that width of column are equal.

However you should not use hard-coded values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM