cambiar la altura de un UICollectionReuseableView (encabezado de sección de colección) dinámicamente


Estoy tratando de establecer la altura de los encabezados de sección para un UICollectionView dinámicamente, pero usando el código a continuación, no veo ningún cambio. La vista se dibuja con los elementos correctos en ella, pero la altura no se moverá. Lo siento si esta es una pregunta repetida, pero parece que no puedo encontrar nada relacionado específicamente con el objeto UICollectionView. Gracias de antemano.

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    PhotoVideoHeaderCell *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                          withReuseIdentifier:@"videoHeaderView"
                                                                                 forIndexPath:indexPath];
    if (indexPath.section == 0) {
        // photos
        [headerView setSection:@"Photo"];
    } else {
        [headerView.VehicleDetailView removeFromSuperview];
        CGRect frame = headerView.frame;
        frame.size.height = 60;
        [headerView setFrame:frame];
        [headerView setNeedsDisplay];
        [headerView setBackgroundColor:[UIColor grayColor]];
        [headerView setSection:@"Video"];
    }

    return headerView;
}
Author: trudyscousin, 2013-01-17

4 answers

Su delegado debe implementar la siguiente función, asumiendo que está utilizando un diseño de flujo:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;

Puede devolver un tamaño diferente para cada encabezado. En las vistas de colección con desplazamiento horizontal, solo se utiliza el ancho. En los que se desplazan verticalmente, solo se usa la altura. El valor no utilizado se ignora: su vista siempre se extenderá para completar la altura/anchura completa de las vistas de colección horizontales/verticales, respectivamente.

Hay un método correspondiente para los pies de página, demasiado.

 68
Author: Ash Furrow,
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
2013-01-17 17:27:29

Respuesta aceptada en Swift 3 y 4:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: collectionView.frame.size.width, height: 250)
}
 2
Author: brandonscript,
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
2017-11-22 20:28:11

Intenta algo como esto:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *header = [siteMapCollection dequeueReusableSupplementaryViewOfKind: UICollectionElementKindSectionHeader withReuseIdentifier: @"headerID" forIndexPath: indexPath];
    NSString *headerText = @"This is my header";
    UIFont *labFont = [UIFont fontWithName: @"HelveticaNeue-CondensedBold" size: 20.0];
    CGSize textSize = [dummyText sizeWithFont: labFont];
    UILabel *headerLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, header.frame.size.height - (textSize.height + 12), header.frame.size.width, textSize.height + 8)];
    [headerLabel setFont: labFont];

    [header addSubview: headerLabel];

    return header;
}
 1
Author: Axeva,
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
2013-01-17 17:16:43

Bueno, en lugar de usar el método noisy delegate, prefiero usar esto: (solo funciona si tiene un tamaño de encabezado único)

    let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout // Assuming you use the default flow layout 
    layout.headerReferenceSize = CGSize(width: 42, height: 42) //Set the header size

Funciona también con el itemSize:

    layout.itemSize = CGSize(width: 42, height: 42) //Set a custom item size

Esto funciona muy bien para establecer un tamaño de elemento en relación con el ancho de la pantalla, por ejemplo.

 1
Author: Antzi,
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
2018-04-05 07:51:52