这是您问题的程序化答案:
通过扩展 UICollectionViewFlowLayout 创建一个类。
在我们类的实现文件中,添加如下方法:
- (instancetype)init
{
self = [super init];
if (self) {
//overriding default values
self.scrollDirection = UICollectionViewScrollDirectionVertical;
self.minimumInteritemSpacing = 0;
self.minimumLineSpacing = 0;
}
return self;
}
//正确排列单元格的方法
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
//Returns an array of UICollectionViewLayoutAttributes objects representing the layout information for the cells and views.
NSArray *attribArray = [super layoutAttributesForElementsInRect:rect];
for(int i = 1; i < [attribArray count]; ++i) {
UICollectionViewLayoutAttributes *currentLayoutAttributes = attribArray[i];
UICollectionViewLayoutAttributes *prevLayoutAttributes = attribArray[i - 1];
//No separation between the cells
NSInteger maximumSpacing = 0;
NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
if((origin + maximumSpacing + currentLayoutAttributes.frame.size.width) < self.collectionViewContentSize.width) {
CGRect frame = currentLayoutAttributes.frame;
frame.origin.x = origin + maximumSpacing;
currentLayoutAttributes.frame = frame;
}
}
return attribArray;
}
//如果collection view bound发生变化,会重新计算其所有的layout属性
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
将此自定义类设置为集合视图的流布局,
YourFLowLayoutCustomClass *flowlayout=[[YourFLowLayoutCustomClass alloc] init];
_collectionView = [[UICollectionView alloc]initWithFrame:frame collectionViewLayout:flowlayout];
现在在你已经实现 UICollectionView 的类中,如果你还没有这样做,请实现以下方法:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(self.view.frame.size.width/2, self.view.frame.size.height/3);
}
这将根据您共享的图片设置单元格的大小。干杯!