Изменяет высоту UICollectionReuseableView (заголовок секции коллекции) динамически
Я пытаюсь установить высоту заголовков раздела для UICollectionView
динамически, но, используя приведенный ниже код, я ничего не вижу. Вид рисуется с помощью правильных элементов, но высота не сдвинется с места. Извините, если это повторяющийся вопрос, но я не могу найти ничего связанного с объектом UICollectionView
. Спасибо заранее.
- (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;
}
Ответы
Ответ 1
Ваш делегат должен реализовать следующую функцию, предполагая, что вы используете раскладку потока:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
Вы можете вернуть другой размер для каждого заголовка. При просмотре коллекции с горизонтальной прокруткой используется только ширина. При вертикальной прокрутке используется только высота. Неиспользованное значение игнорируется - ваше представление всегда будет растянуто для заполнения полной высоты/ширины представлений горизонтальной/вертикальной коллекции соответственно.
Существует также соответствующий метод для нижних колонтитулов.
Ответ 2
Попробуйте что-то вроде этого:
- (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;
}
Ответ 3
Принятый ответ в Swift 3 и 4:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.size.width, height: 250)
}