UICollectionView 布局像 SnapChat? [英] UICollectionView Layout like SnapChat?

查看:24
本文介绍了UICollectionView 布局像 SnapChat?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何像 SnapChat 的故事一样创建 UICollectionViewLayout?

有什么想法吗?

我想要一个没有外部库的解决方案.

解决方案

基于

旁注:调整逻辑或进行更改取决于您,单元格框架计算可能不是最好看的代码".

how do we create a UICollectionViewLayout like the SnapChat's stories?

Any ideas please?

I'd like to have a solution without external library.

解决方案

Based on a precedent answer adapted to your issue:

-(id)initWithSize:(CGSize)size
{
  self = [super init];
  if (self)
  {
      _unitSize = CGSizeMake(size.width/2,80);
      _cellLayouts = [[NSMutableDictionary alloc] init];
  }
  return self;
}
-(void)prepareLayout
{
    for (NSInteger aSection = 0; aSection < [[self collectionView] numberOfSections]; aSection++)
    {

        //Create Cells Frames
        for (NSInteger aRow = 0; aRow < [[self collectionView] numberOfItemsInSection:aSection]; aRow++)
        {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:aRow inSection:aSection];
            UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

            NSUInteger i = aRow%3;
            NSUInteger j = aRow/3;
            CGFloat offsetY = _unitSize.height*2*j;
            CGPoint xPoint;
            CGFloat height = 0;
            BOOL invert = NO;
            if (aRow%6 >= 3) //We need to invert Big cell and small cells => xPoint.x
            {
                invert = YES;
            }
            switch (i)
            {
                case 0:
                    xPoint = CGPointMake((invert?_unitSize.width:0), offsetY);
                    height = _unitSize.height;
                    break;
                case 1:
                    xPoint = CGPointMake((invert?_unitSize.width:0), offsetY+_unitSize.height);
                    height = _unitSize.height;
                    break;
                case 2:
                    xPoint = CGPointMake((invert?0:_unitSize.width), offsetY);
                    height = _unitSize.height*2;
                    break;
                default:
                    break;
            }

            CGRect frame = CGRectMake(xPoint.x, xPoint.y, _unitSize.width, height);
            [attributes setFrame:frame];
            [_cellLayouts setObject:attributes forKey:indexPath];
        }

    }
}

I set the height of unitSize to 80, but you can use the size of the screen if needed, like _unitSize = CGSizeMake(size.width/2,size.height/4.);.

That render:

Side note: It's up to you to adapt the logic, or do changes, the cell frames calculation may not be the "best looking piece of code".

这篇关于UICollectionView 布局像 SnapChat?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆