答案 0 :(得分:0)
您需要使用UICollectionViewDelegateFlowLayout
方法
extension HomeVC: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 16
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (collectionView.bounds.size.width)/2 - 8 , height: (collectionView.bounds.size.width)/2 )
}
}
minimumInteritemSpacingForSectionAt方法是单元格之间的间距。
答案 1 :(得分:0)
- (void)viewDidLoad {
[super viewDidLoad];
self.data = @[@[[UIColor blackColor],[UIColor blackColor],[UIColor blackColor]], //section 1
@[[UIColor yellowColor],[UIColor yellowColor],[UIColor yellowColor]]]; //section 2
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
[self.collectionView setContentInset:UIEdgeInsetsMake(8, 8, 8, 8)];
[self setupCollectionViewCellSize];
}
- (void)setupCollectionViewCellSize {
int numOfCell = 2, paddingBetweenCell = 8;
float width = [UIScreen mainScreen].bounds.size.width - (self.collectionView.contentInset.left + self.collectionView.contentInset.right); //minus left and right Inset
float cellWidth = (width - (numOfCell * paddingBetweenCell)) / numOfCell;
self.cellSize = CGSizeMake(cellWidth, cellWidth);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return self.cellSize;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [[self.data objectAtIndex:0] count] + [[self.data objectAtIndex:1] count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
if(indexPath.item%2==0) {
cell.backgroundColor = [[self.data objectAtIndex:0] objectAtIndex: (indexPath.item%[[self.data objectAtIndex:0] count])];
} else {
cell.backgroundColor = [[self.data objectAtIndex:1] objectAtIndex: (indexPath.item%[[self.data objectAtIndex:1] count])];
}
return cell;
}