tutorial collection ios objective-c uicollectionview uicollectionviewcell

ios - tutorial - uicollectionview swift 4



Ancho de celda dinĂ¡mico de UICollectionView dependiendo del ancho de la etiqueta (6)

Tengo un UICollectionView, que carga celdas desde una celda reutilizable, que contiene una etiqueta. Una matriz proporciona contenido para esa etiqueta. Puedo cambiar el ancho de la etiqueta dependiendo del ancho del contenido fácilmente con sizeToFit. Pero no puedo hacer celular para encajar etiqueta.

Aquí está el código

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. arrayOfStats = @[@"time:",@"2",@"items:",@"10",@"difficulty:",@"hard",@"category:",@"main"]; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection: (NSInteger)section{ return [arrayOfStats count]; } - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ return CGSizeMake(??????????); } - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return 1; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ Cell *cell = (Cell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath]; cell.myLabel.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]]; // make label width depend on text width [cell.myLabel sizeToFit]; //get the width and height of the label (CGSize contains two parameters: width and height) CGSize labelSize = cell.myLbale.frame.size; NSLog(@"/n width = %f height = %f", labelSize.width,labelSize.height); return cell; }


// agregar en la vista

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal]; layout.estimatedItemSize = CGSizeMake(self.breadScrumbCollectionView.frame.size.width, 30); self.breadScrumbCollectionView.collectionViewLayout = layout;


En sizeForItemAtIndexPath devuelve el tamaño del texto

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ return [(NSString*)[arrayOfStats objectAtIndex:indexPath.row] sizeWithAttributes:NULL]; }


En swift 3

let size = (arrayOfStats[indexPath.row] as NSString).size(attributes: nil)


Verifique abajo el código que podría estar dando CGSize muy corto.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ NSString *testString = @"SOME TEXT"; return [testString sizeWithAttributes:NULL]; }


Swift 4.2+

El principio es:

  1. Implementar UICollectionViewDelegateFlowLayout (contiene la firma del método necesario)

  2. Llame a collectionView...sizeForItemAt método.

  3. No es necesario hacer un puente de String a NSString para llamar al size(withAttributes: . Swift String tiene fuera de la caja).

  4. Los atributos son los mismos que configuró para (NS)AttributedString , es decir, familia de fuentes, tamaño, peso, etc. Parámetro opcional.

Solución de muestra:

extension ViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return "String".size(withAttributes: nil) } }

Pero lo más probable es que desee especificar atributos de cadena concretos correspondientes a su celda, por lo que la devolución final se vería así:

// Replace "String" with proper string (typically array element). return "String".size(withAttributes: [ NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14) ])


Swift 4

let size = (arrayOfStats[indexPath.row] as NSString).size(withAttributes: nil)