谁能指出我如何使用 UICollectionViewLayout 创建类似于 Pinterest 列布局的界面的正确方向?
我尝试在网上搜索,但似乎还没有很多例子。
谁能指出我如何使用 UICollectionViewLayout 创建类似于 Pinterest 列布局的界面的正确方向?
我尝试在网上搜索,但似乎还没有很多例子。
1000memories “Quilt” 视图类似于 pinterest 并且是开源的:http ://blog.1000memories.com/168-opensourcing-quilt ,您可以深入了解它是如何工作的。
如果您正在寻找更概念性的概述,这里是您想要做什么的基本概念。到目前为止,如果您只需要 Pinterest 风格的布局,最简单的事情就是子类化UICollectionViewFlowLayout
. 你可以从这个类中获得很多布局帮助,Pinterest 风格在它的能力范围内。您只需要覆盖一种方法。
使用 UICollectionViewFlow 布局设置一个普通的 UICollectionView。一个快速的方法是:
(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
(NSInteteger)collectionView:numberOfItemsInSection:
(UICollectionViewCell *)collectionView:cellForItemAtIndexPath:
dequeueReusableCellWithReuseIdentifier:forIndexPath:
使用索引路径调用。如果您向单元格添加了 UIImageView 或一些标签,这将是实际分配图像、文本等的好地方。在 viewController 的viewDidLoad
实例化 aUICollectionViewFlowLayout
并将 UICollectionView 的数据源设置为您的,并将布局设置为 flowlayout。请记住,这个类是UICollectionViewViewController
.
self.collectionView.dataSource = [[YourDataSource alloc] init];
self.collectionView.collectionViewLayout = [[UICollectionViewFlowLayout alloc] init];
好的。此时,您应该能够运行您的应用程序并在屏幕上看到一些内容。这是一个旋风式的概述。如果您需要有关如何设置 ViewController 等的更多详细信息,那么有很多可用的资料。
现在到了重要的部分,Pinterest 化流布局。
首先,添加一个新类,它是 UIViewControllerFlowLayout 的子类。更改您的 ViewControllerviewDidLoad
以实例化此类并分配为UICollectionView
's collectionViewLayout
。
您将需要实现的方法是- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
.
事情是这样的:超类将为您完成几乎所有的工作。您的代码将如下所示:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
[attributes enumerateObjectsUsingBlock:^(id attr, NSUInteger idx, BOOL *stop) {
float newYCoord = [calculationMethodYouHaveToWriteFor:attr.frame];
attr.frame = CGRectMake(attr.frame.origin.x, newYCoord, attr.size.width, attr.size.height];
}];
}
Pinterest 使用固定宽度的列,您在计算方法中需要做的就是找出您所在的列(`attr.origin.x / _columnWidth),然后从您的 ivar 中查找该列的总高度一直保存它。不要忘记将它添加到新对象的高度并将其保存回来以供下一次通过。
流布局超类处理:制作单元格,确定哪些单元格可见,确定内容大小,确定行在 x 方向上的排列,为单元格分配索引路径。很多垃圾。压倒这一种方法可以让您根据自己的心愿摆弄 y-pos。
来自github的两个
https://github.com/jayslu/JSPintDemo
https://github.com/chiahsien/UICollectionViewWaterfallLayout
我现在在一个项目中使用了 Waterfall 的修改版本,我现在正在研究 JSPint。
我创建了一个自定义 uicollectionviewlayout,用于我的个人项目。链接在这里。希望能帮助到你。
你可以从这里得到你想要的任何东西: https ://github.com/ParsifalC/CPCollectionViewKit 例如(这两个布局都是自定义 UICollectionViewLayout):