設(shè)計要求CollectionView水平窥妇、垂直方向的間隔均為0.5pt時舷胜,該如何實現(xiàn),按正常思路活翩,設(shè)置
collectionViewLayout.minimumLineSpacing = 0.5;
collectionViewLayout.minimumLineSpacing = 0.5;
image.png
最終運行的結(jié)果烹骨,實際間隔并沒有均勻分布,有的是1px材泄,有的大于1px沮焕。導(dǎo)致出現(xiàn)這種問題的原因是:
平分屏幕的時候,itemSize.width = (375-30)/4=86.25(iphone8為例:1px=0.5pt)拉宗,計算的寬度小數(shù)后竟然是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;
// 根據(jù)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);
}
運行結(jié)果:
image.png
補充
開發(fā)中如果UI要求分割線是1px,不管是label姐浮、tableViewCell最好使用(1/[UIScreen mainScreen].scale)
谷遂,不要寫成0.5了。