Espaciado de celdas en UICollectionView

Resuelto Vishal Singh asked hace 54 años • 27 respuestas

¿Cómo configuro el espacio entre celdas en una sección de UICollectionView? Sé que hay una propiedad. minimumInteritemSpacingLa configuré en 5.0 pero el espaciado no aparece 5.0. He implementado el método de delegado flowout.

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{

    return 5.0;
}

Todavía no obtengo el resultado deseado. Creo que es el espacio mínimo. ¿No hay alguna forma de establecer el espacio máximo?

simulador sc

Vishal Singh avatar Jan 01 '70 08:01 Vishal Singh
Aceptado

Apoyando la pregunta inicial. Intenté conseguir el espaciado a 5px en UICollectionViewpero esto no funciona, también con un UIEdgeInsetsMake(0,0,0,0)...

En UITableView puedo hacer esto especificando directamente las coordenadas x,y en una fila...

ingrese la descripción de la imagen aquí

Aquí está mi código UICollectionView:

#pragma mark collection view cell layout / size
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self getCellSize:indexPath];  // will be w120xh100 or w190x100
    // if the width is higher, only one image will be shown in a line
}

#pragma mark collection view cell paddings
- (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0); // top, left, bottom, right
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {

    return 5.0;
}

Actualización: Resolvió mi problema, con el siguiente código.

ingrese la descripción de la imagen aquí

VerControlador.m

#import "ViewController.h"
#import "MagazineCell.h" // created just the default class. 

static NSString * const cellID = @"cellID";

@interface ViewController ()

@end

@implementation ViewController

#pragma mark - Collection view
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 30;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MagazineCell *mCell = (MagazineCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];

    mCell.backgroundColor = [UIColor lightGrayColor];

    return mCell;
}

#pragma mark Collection view layout things
// Layout: Set cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    NSLog(@"SETTING SIZE FOR ITEM AT INDEX %d", indexPath.row);
    CGSize mElementSize = CGSizeMake(104, 104);
    return mElementSize;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 2.0;
}

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

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

@end
jerik avatar Jul 09 '2013 17:07 jerik

Sé que el tema es antiguo, pero en caso de que alguien todavía necesite la respuesta correcta, aquí lo que necesita:

  1. Anular el diseño de flujo estándar.
  2. Agregue una implementación así:

    - (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
        NSArray *answer = [super layoutAttributesForElementsInRect:rect];
    
        for(int i = 1; i < [answer count]; ++i) {
            UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
            UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];
            NSInteger maximumSpacing = 4;
            NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
    
            if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
                CGRect frame = currentLayoutAttributes.frame;
                frame.origin.x = origin + maximumSpacing;
                currentLayoutAttributes.frame = frame;
            }
        }
        return answer;
    }
    

donde el espacio máximo se puede establecer en cualquier valor que prefiera. ¡¡Este truco garantiza que el espacio entre celdas sea EXACTAMENTE igual al Espaciado máximo!!

iago849 avatar Oct 17 '2013 14:10 iago849

Usando un diseño de flujo horizontal, también obtuve un espacio de 10 puntos entre celdas. Para eliminar el espaciado necesitaba establecerlo minimumLineSpacingy ponerlo minimumInterItemSpacinga cero.

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

Además, si todas las celdas tienen el mismo tamaño, es más sencillo y eficiente establecer la propiedad en el diseño de flujo directamente en lugar de utilizar métodos delegados.

Jason Moore avatar May 08 '2014 12:05 Jason Moore

Recuerde, es un espacio de línea mínimo , no un espacio mínimo entre elementos o espacio de celda. Porque la dirección de desplazamiento de su colección View es HORIZONTAL .

Si es vertical, entonces necesita establecer el espacio de celda o el espacio entre elementos para el espacio horizontal entre celdas y el interlineado para el espacio vertical entre celdas.

Versión Objective-C

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

Versión rápida:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 20
}
Vincent Joy avatar Dec 12 '2015 15:12 Vincent Joy