有人能告诉我如何使用UICollectionViewLayout创建一个类似于Pinterest列布局的界面吗?
我试着在网上搜索,但看起来还没有太多的例子。
发布于 2013-06-21 10:20:26
1000Memory的“被子”视图类似于pinterest,并且是开源的:http://blog.1000memories.com/168-opensourcing-quilt,你可以通过它来深入了解它是如何工作的。
如果你正在寻找一个更概念性的概述,这里是你想要做的基本想法。到目前为止,如果你只需要一个Pinterest风格的布局,最简单的事情就是继承UICollectionViewFlowLayout的子类。你可以从这个类得到很多布局帮助,Pinterest风格也在它的能力范围之内。你只需要重写一个方法。
使用UICollectionViewFlow布局设置普通UICollectionView。一种快速的方法是:
,
(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
1. `(NSInteteger)collectionView:numberOfItemsInSection:`
- hardcode a number for now, make it 20.
1. – `(UICollectionViewCell *)collectionView:cellForItemAtIndexPath:`
- This is one of the places where subclassing the flow layout's gonna do you a favor. All you really need to do here is call `dequeueReusableCellWithReuseIdentifier:forIndexPath:` with the index path. If you added a UIImageView or some labels to the cell, this would be a great place to actually assign the image, text, etc.
视图控制器的viewDidLoad中的
UICollectionViewFlowLayout,并将UICollectionView的数据源设置为您的,将布局设置为flowlayout。记住,这个类是UICollectionViewViewController的子类。self.collectionView.dataSource = [YourDataSource分配初始化];self.collectionView.collectionViewLayout = [UICollectionViewFlowLayout分配初始化];
好的。此时,您应该能够运行您的应用程序并在屏幕上看到一些内容。这是一个旋风式的概述。如果您需要更多关于如何设置ViewControllers的详细信息,等等,您可以找到大量的相关资料。
现在到了重要的部分,Pinterest- flow布局。
首先,添加一个新类,它是UIViewControllerFlowLayout的子类。更改视图控制器的viewDidLoad以实例化该类,并将其指定为UICollectionView的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。
发布于 2012-11-27 22:30:32
以下是来自github的两篇文章
https://github.com/jayslu/JSPintDemo
https://github.com/chiahsien/UICollectionViewWaterfallLayout
我现在已经在一个项目中使用了一个修改过的瀑布版本,现在我正在研究JSPint。
发布于 2014-08-27 15:24:02
我创建了一个自定义的uicollectionviewlayout布局,用于我的个人项目中。这是链接。希望能有所帮助。
https://stackoverflow.com/questions/13360973
复制相似问题