Как удалить границу между двумя столбцами UICollectionView

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

enter image description here

код

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

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

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

Дополнительные сведения

  • Ширина ячейки 234
  • Ширина UICollectionView равна 703

Ответы

Ответ 1

Из этого. Вам нужно изменить minimumInteritemSpacing и minimumLineSpacing.

UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
flow.itemSize = CGSizeMake(cellWidth, cellHeight);
flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flow.minimumInteritemSpacing = 0;
flow.minimumLineSpacing = 0;
mainCollectionView.collectionViewLayout = flow;

Ответ 2

Ниже был трюк для меня.

UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
flow.itemSize = CGSizeMake(360*iPhoneFactorX, 438*iPhoneFactorX);
flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flow.minimumInteritemSpacing = 0;
flow.minimumLineSpacing = 0;


[mainCollectionView reloadData];
mainCollectionView.collectionViewLayout = flow;

Последняя строка очень важна, когда мы назначаем макет

Ответ 3

Вы не можете сделать это с помощью UICollectionViewFlowLayout по умолчанию. Хотя вы можете использовать другой макет, например, его подкласс. Я использую этот класс, чтобы установить интервал явно:

@implementation FlowLayoutExt
@synthesize maxCellSpacing;

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray* attributesToReturn = [super layoutAttributesForElementsInRect:rect];
    for (UICollectionViewLayoutAttributes* attributes in attributesToReturn) {
        if (nil == attributes.representedElementKind) {
            NSIndexPath* indexPath = attributes.indexPath;
            attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
        }
    }
    return attributesToReturn;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes* currentItemAttributes =
    [super layoutAttributesForItemAtIndexPath:indexPath];

    UIEdgeInsets sectionInset = [(UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout sectionInset];

    if (indexPath.item == 0) { // first item of section
//        CGRect frame = currentItemAttributes.frame;
//        frame.origin.x = sectionInset.left; // first item of the section should always be left aligned
//        currentItemAttributes.frame = frame;

        return currentItemAttributes;
    }

    NSIndexPath* previousIndexPath = [NSIndexPath indexPathForItem:indexPath.item-1 inSection:indexPath.section];
    CGRect previousFrame = [self layoutAttributesForItemAtIndexPath:previousIndexPath].frame;
    CGFloat previousFrameRightPoint = previousFrame.origin.x + previousFrame.size.width + maxCellSpacing;

    CGRect currentFrame = currentItemAttributes.frame;
    CGRect strecthedCurrentFrame = CGRectMake(0,
                                              currentFrame.origin.y,
                                              self.collectionView.frame.size.width,
                                              currentFrame.size.height);

    if (!CGRectIntersectsRect(previousFrame, strecthedCurrentFrame)) { // if current item is the first item on the line
        // the approach here is to take the current frame, left align it to the edge of the view
        // then stretch it the width of the collection view, if it intersects with the previous frame then that means it
        // is on the same line, otherwise it is on it own new line
        CGRect frame = currentItemAttributes.frame;
        frame.origin.x = sectionInset.left; // first item on the line should always be left aligned
        currentItemAttributes.frame = frame;
        return currentItemAttributes;
    }

    CGRect frame = currentItemAttributes.frame;
    frame.origin.x = previousFrameRightPoint;
    currentItemAttributes.frame = frame;
    return currentItemAttributes;
}

Ответ 4

Я установил аналогичную проблему, сняв флажок " Относительно поля" в инспекторе размеров.

введите описание изображения здесь

Измените интервал в storyBoard или программно.

введите описание изображения здесь

или

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

Ответ 5

Попробуйте установить 0 (ноль) в свойства UICollectionView: Минимальное расстояние для ячеек и строк

Ответ 6

На самом деле, вы не сможете установить параметр для достижения своей цели, используя UICollectionViewFlowLayout, потому что он играет с интервалом между ячейками, чтобы правильно выровнять все элементы на экране и что причина, по которой они устанавливают расстояние между ячейками, как минимум. Если размер вашей ячейки исправлен, вы можете играть с ViewCollection Size, чтобы все ячейки и поля полностью вписывались в него.