2017-09-16 21 views
0

與補充視圖添加頁眉到UiCollectionView我有一個視圖控制器包含一個的CollectionView:如何在Objective-C

- (void)viewDidLoad 
{ 
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new]; 
    collectionview = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout]; 
    collectionview.backgroundColor = [UIColor colorWithRed:0.86 green:0.86 blue:0.86 alpha:1.0]; 
    collectionview.translatesAutoresizingMaskIntoConstraints = false; 
    collectionview.delegate = self; 
    collectionview.dataSource = self; 
    collectionview.bounces = true; 
    [collectionview registerClass:[CollectionViewCell1 class] forCellWithReuseIdentifier:@"cell1"]; 
    [self.view addSubview:collectionview]; 
    [collectionview sdc_alignEdgesWithSuperview:UIRectEdgeAll]; 
    [collectionview registerClass:[RecipeCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"]; 
} 

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionReusableView *reusableview = nil; 
    RecipeCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath]; 
    headerView.backgroundColor = [UIColor greenColor]; 
    headerView.title.text = @"ABC"; 
    reusableview = headerView; 

    return reusableview; 
} 

和RecipeCollectionReusableView是:

- (void)initialize 
{ 
    _title = [UILabel new]; 
    _title.translatesAutoresizingMaskIntoConstraints = false; 
    [self addSubview:_title]; 
    [_title sdc_centerInSuperview]; 
} 

但沒有任何頭在運行後在屏幕上。

回答

0

你是否對頭做了必要的實現?

https://developer.apple.com/documentation/uikit/uicollectionviewdelegateflowlayout/1617702-collectionview?language=objc

的CollectionView:佈局:referenceSizeForHeaderInSection:

返回值 標頭的大小。如果您返回大小(0,0)的值,則不會添加標頭。

討論 如果不實現此方法,流程佈局使用其 headerReferenceSize 屬性的值來設置標題的大小。 在佈局過程中,只使用與相應滾動方向相對應的大小。例如,對於垂直滾動方向,佈局對象使用方法返回的高度值。 (在這種情況下,標題的寬度將設置爲集合視圖的寬度。)如果相應滾動維度中的大小爲0,則不會添加標題。