如何在屏幕的左侧和第二部分右侧显示第一部分的UICollectionView

时间:2018-05-31 13:19:05

标签: ios objective-c iphone uicollectionview

我想创建一个UICollectionView,其第一部分位于屏幕左侧,第二部分位于屏幕右侧,如两列。对于每个部分,我需要一个部分标题。 有没有办法实现这个或任何其他方式。enter image description here

2 个答案:

答案 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;
}