我正在尝试创建一个类似于下图的 Collection View 。中心项目将始终具有“焦点”并且更大,这有点像封面流概念:
http://s13.postimg.org/n6vzil213/layout_schematic.png
我可以使用 UICollectionViewFlowLayout 实现此目的,但我希望底部单元格 (3) 在我滚动时以更大的动画显示,而中间单元格 (2) 以较小的动画显示?我假设我需要用 ScrollView 委托(delegate)方法做一些数学运算。
关于如何实现这一点有什么想法吗?
最佳答案
您可以仅通过子类化 UICollectionViewFlowLayout 来做到这一点。
步骤如下:
- 创建一个 UICollectionViewFlowLayout 子类
- 覆盖 shouldInvalidateLayoutForBoundsChange: 并返回 YES
- 覆盖 layoutAttributesForElementsInRect: 和 layoutAttributesForItemAtIndexPath:。调用 super 实现以获取标准 FlowLayout 值。
- 创建一个方法,步骤 #3 中的两个方法都会调用该方法,该方法看起来会根据项目与 Collection View 中心的距离改变其布局属性。使用数学为项目设置正确的 itemSize/变换/3D 变换。
这是一个 super 粗略的例子,它可以做你正在寻找的事情,没有正确的数学。
@implementation MMLayout
-(CGSize)itemSize
{
return CGSizeMake(200.0f, 200.0f);
}
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *atts in attributes) {
[self scaleForPositionOfAttributes:atts];
}
return attributes;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
{
UICollectionViewLayoutAttributes *atts = [super layoutAttributesForItemAtIndexPath:indexPath];
[self scaleForPositionOfAttributes:atts];
return atts;
}
- (void)scaleForPositionOfAttributes:(UICollectionViewLayoutAttributes *)attributes
{
CGFloat collectionViewHeight = CGRectGetHeight(self.collectionView.bounds);
CGFloat collectionViewCenter = collectionViewHeight / 2.0f;
CGFloat scaleForCenter = ABS(collectionViewCenter - (attributes.frame.origin.y - self.collectionView.contentOffset.y)) < 50.0f ? 1.3f : 0.7f;
attributes.size = CGSizeMake(200.0f * scaleForCenter, 200.0f * scaleForCenter);
}
@end
关于ios - 创建自定义 Collection View 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25253436/