Подтвердить что ты не робот

Добавление прокладки к первой и последней ячейке UICollectionView

Я подкласс UICollectionViewFlowLayout, чтобы получить горизонтальный UICollectionView с поведением, подобным подкачки. Он прекрасно работает до тех пор, пока UICollectionViewCell не является первой из последней ячейки. Изображения прилагаются ниже.

enter image description here enter image description here

Нужно ли что-то переопределять в моем UICollectionViewFlowLayout, кроме следующего?

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
CGFloat offSetAdjustment = MAXFLOAT;
CGFloat horizontalCenter = (CGFloat) (proposedContentOffset.x + (self.collectionView.bounds.size.width / 2.0));

CGRect targetRect = CGRectMake(proposedContentOffset.x,
                               0.0,
                               self.collectionView.bounds.size.width,
                               self.collectionView.bounds.size.height);

NSArray *array = [self layoutAttributesForElementsInRect:targetRect];
for (UICollectionViewLayoutAttributes *layoutAttributes in array)
{
    if(layoutAttributes.representedElementCategory == UICollectionElementCategoryCell)
    {
        CGFloat itemHorizontalCenter = layoutAttributes.center.x;
        if (ABS(itemHorizontalCenter - horizontalCenter) < ABS(offSetAdjustment))
        {
            offSetAdjustment = itemHorizontalCenter - horizontalCenter;
        }
    }
}

CGFloat nextOffset = proposedContentOffset.x + offSetAdjustment;

do {
    proposedContentOffset.x = nextOffset;
    CGFloat deltaX = proposedContentOffset.x - self.collectionView.contentOffset.x;
    CGFloat velX = velocity.x;

    if(deltaX == 0.0 || velX == 0 || (velX > 0.0 && deltaX > 0.0) || (velX < 0.0 && deltaX < 0.0))
    {
        break;
    }

    if(velocity.x > 0.0)
    {
        nextOffset += [self snapStep];
    }
    else if(velocity.x < 0.0)
    {
        nextOffset -= [self snapStep];
    }
} while ([self isValidOffset:nextOffset]);

proposedContentOffset.y = 0.0;

return proposedContentOffset;
}
    - (BOOL)isValidOffset:(CGFloat)offset
{
    return (offset >= [self minContentOffset] && offset <= [self maxContentOffset]);
}

- (CGFloat)minContentOffset
{
  return -self.collectionView.contentInset.left;
}

- (CGFloat)maxContentOffset
{
    return [self minContentOffset] + self.collectionView.contentSize.width -      self.itemSize.width;
}

- (CGFloat)snapStep
{
return self.itemSize.width + self.minimumLineSpacing;
}

Любые указатели/комментарии будут полезны.

4b9b3361

Ответ 1

Вы можете установить пространство слева и справа равным отступу при настройке фрейма представления коллекции.

или

Вы можете поставить условие в cellForItemAtIndexPath, чтобы, если это первая ячейка или последняя ячейка, соответственно управляли дополнением. что это.

Или

Вы можете установить свойство contentInset вашего collectionView.

например,

UICollectionView *cv; // your collectionView

cv.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);

В качестве альтернативы вы можете установить UICollectionView contentInset в раскадровке, чтобы заставить его работать.

Ответ 2

Вы можете достичь этого, изменив вкладки в Интерфейсном Разработчике. Их можно найти как вкладки сечений в инспекторе размеров:

Section Insets for Collection View in InterfaceBuilder

Ответ 3

Для Swift 5:

В вашем viewDidLoad установите свойство contentInset для collectionView следующим образом:

self.collectionView.contentInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);

Ответ 4

simple вы можете использовать методы коллекционирования для установки UIEdgeInsets, например, метода bellow.

-(UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
  return UIEdgeInsetsMake(0,10,0,10); // top, left, bottom, right
}

здесь вы можете передать значение для левого пространства и правого пространства для первой и последней ячейки, вы также можете предоставить минимальное пространство между двумя ячейками через следующий метод

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
   return 5.0;
}

Ответ 5

Принятое решение работает, но , если вы включили pagingEnabled, подкачка представления коллекции не работает.

Для меня решение было использовать:


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
}