最佳答案
编辑
此答案适用于基于大的第一张图像和较小的后一张图像的单一布局的原始问题。
这真的很简单......我没有打扰 iOS 版本,我在下面给出的内容需要大量额外的工作,但至少它会给你一个想法。
Storyboard
在 Storyboard中,我实际上只是在集合 View 中设置了两个项目。一张大图和一张小图。你可以很容易地用一个来完成,这里我使用两个,这样我就可以在 Storyboard中加载图像,而不必费心配置单元格。
希望下面的图片能帮助你理解我的意思。还要注意水平滚动。
收藏 View
这是光秃秃的骨头。当然,它需要工作。特别是我不进行单元配置,而是在没有任何配置的情况下出列并直接返回单元。您需要通过加载应为其显示的图像来配置每个单元格。
我在 Storyboard中定义的两种单元格类型称为 imgLarge
和 imgSmall
.注意我也使用相同的项目标识符。
这里最重要的事情,真正使它起作用的是最后一条消息,在这里我为两个不同的单元格返回两种不同的大小。
#import "TestCollectionViewController.h"
@interface TestCollectionViewController () < UICollectionViewDataSource, UICollectionViewDelegateFlowLayout >
@end
@implementation TestCollectionViewController
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
self.collectionView.collectionViewLayout.invalidateLayout;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
}
#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
if ( indexPath.row )
{
return [collectionView dequeueReusableCellWithReuseIdentifier:@"imgSmall" forIndexPath:indexPath];
}
else
{
return [collectionView dequeueReusableCellWithReuseIdentifier:@"imgLarge" forIndexPath:indexPath];
}
}
#pragma mark <UICollectionViewDelegate>
- ( CGSize ) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat h = collectionView.bounds.size.height;
if ( indexPath.row )
{
return CGSizeMake( h / 2, h / 2 );
}
else
{
return CGSizeMake ( h, h );
}
}
@end
这实际上是第二个版本。第一个版本在这里只使用了常量。由于它们是计算出来的,要使其工作,您需要将 Storyboard中的所有间距和插图设置为 0。结果
瞧!
我提到这是第二个版本。上一个看起来略有不同,如下所示。我保留了图像,对于早期的代码,只需查看这篇文章的历史即可。
关于ios - 如何自定义 UICollectionView Cell 以显示如附件所示的图像网格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64537222/