Diferente tamaño de celda en UICollectionView


En mi aplicación para iphone,estoy mostrando imágenes en una vista de colección. Obtengo las imágenes de las URL, con las url también obtengo el tamaño de la imagen. por ejemplo: - digamos que hay dos tipos de imágenes paisaje y retrato.Obtengo el valor P para imágenes de retrato y L para imágenes de paisaje

¿Cómo personalizar el tamaño de la celda collectionView ?

Author: New Jango Tester, 2013-04-17

4 answers

Utilice este UICollectionViewDelegateFlowLayout método

 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
 64
Author: Anil Varghese,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-19 05:25:51

1) Puede mantener e intercambiar varios objetos de presentación, pero hay una forma más sencilla. Simplemente agregue lo siguiente a su subclase UICollectionViewController y ajuste los tamaños según sea necesario:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{    
    // Adjust cell size for orientation
    if (UIDeviceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
        return CGSizeMake(170.f, 170.f);
    }
    return CGSizeMake(192.f, 192.f);
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [self.collectionView performBatchUpdates:nil completion:nil];
}

Llamar a -performBatchUpdates:completion: invalidará el diseño y redimensionará las celdas con animación (solo puede pasar nil a ambos parámetros de bloque si no tiene ajustes adicionales que realizar).

2) En lugar de codificar los tamaños de los elementos en -collectionView:layout:sizeForItemAtIndexPath, simplemente divida la altura o el ancho de la vista de colección límites por el número de celdas que desea que quepan en la pantalla. Utilice la altura si su UICollectionView se desplaza horizontalmente o la anchura si se desplaza verticalmente.

 9
Author: user3124624,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-05 16:14:34

Esto es lo que hice. Me ajustar el tamaño de la celda en función del tamaño de la pantalla (para que podamos obtener el mejor número de imágenes en cada fila). Es posible que desee cambiar los números para adaptarse a su causa.

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
CGFloat widthOfCell =(self.view.frame.size.width-30)/2;
CGFloat heightOfCell =widthOfCell * 1.33;
CGSize returnValue = CGSizeMake(widthOfCell, heightOfCell);
returnValue.height += 5; 
returnValue.width += 5; 
return returnValue;

}

Luego utilicé un método de manipulación de imágenes para determinar el estado horizontal o vertical, y (para mi aplicación) decidí hacer de cada imagen un retrato:

    if (sourceImage.size.width>sourceImage.size.height) {
    sourceImage = [[UIImage alloc] initWithCGImage: sourceImage.CGImage
                                             scale: 1.0
                                       orientation: UIImageOrientationRight];
    }

Si quieres tenerlo al revés, cambia el > por <

ADVERTENCIA: mi método de rotación no tiene en cuenta si la imagen apunta a la izquierda o a la derecha. En otras palabras, si una imagen es horizontal al revés, mi código no puede reconocerlo. Espero que alguien más pueda ayudarte, ¡y espero no haberme descarrilado! :)

 2
Author: Septronic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-06 23:48:06

Para swift extienda el flowlayout a su viewcontroller, si necesita mostrar imágenes dinámicas en la celda haga variable que mantenga el nombre de las imágenes en su vista contorller y use esto:

let imageData = ["image1","image2","image3","image4"]

extension yourViewController: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let photo = UIImage(named: imageData[indexPath.row])
        return CGSize(width: (photo?.size.width)!, height: (photo?.size.height)!)

}

}

 1
Author: bikram sapkota,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-09 14:24:51