UICollectionView-调整间隔

设计要求CollectionView水平、垂直方向的间隔均为0.5pt时,该如何实现,按正常思路,设置

collectionViewLayout.minimumLineSpacing = 0.5;
collectionViewLayout.minimumLineSpacing = 0.5;
image.png

最终运行的结果,实际间隔并没有均匀分布,有的是1px,有的大于1px。导致出现这种问题的原因是:
平分屏幕的时候,itemSize.width = (375-30)/4=86.25(iphone8为例:1px=0.5pt),计算的宽度小数后竟然是0.25,小于1像素是不可再分割的。
实际1px = (1/[UIScreen mainScreen].scale);

修改后的代码:

// #define PixelValue  (1/[UIScreen mainScreen].scale)

- (void)configCollectionView {
    collectionRows = 4;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = PixelValue;
    layout.minimumInteritemSpacing = PixelValue;
    layout.sectionInset = UIEdgeInsetsMake(PixelValue, PixelValue, PixelValue, PixelValue);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    
    CGFloat originalWidth = self.view.frame.size.width-30;
    
    NSInteger itemWidth = roundf((originalWidth-5*PixelValue)/4.0); // 四舍五入
    CGFloat firstWidth = originalWidth-itemWidth*3-5*PixelValue;
    firstWidth = floorf(firstWidth)+PixelValue;
    
// 根据itemSize和间隔去更新collectionView的frame
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(15, 50, itemWidth*3+firstWidth+5*PixelValue, (82+PixelValue)*collectionRows+PixelValue) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor darkGrayColor];
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[TempCollectionViewCell class] forCellWithReuseIdentifier:@"TempCollectionViewCell"];
}

// 保证1px间隔的同时,也要保证每个item的宽度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat originalWidth = self.view.frame.size.width-30;
    NSInteger width = roundf((originalWidth-5*PixelValue)/4.0); // 四舍五入
    if (indexPath.row % 4 == 3) {
        CGFloat firstWidth = originalWidth-width*3-5*PixelValue;
        firstWidth = floorf(firstWidth)+PixelValue;
        return CGSizeMake(firstWidth, 82);
    }
    return CGSizeMake(width, 82);
}

运行结果:


image.png

补充
开发中如果UI要求分割线是1px,不管是label、tableViewCell最好使用(1/[UIScreen mainScreen].scale),不要写成0.5了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容