iOS collectionView自定義head和foot


1.新建2個view繼承自UICollectionReusableView

2.view里實現你想展現的控件

3.viewdidload里實現

[self.collectionView registerClass:[HeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];

[self.collectionView registerClass:[FootView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"foot"];

4.實現方法:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

{

    if (kind == UICollectionElementKindSectionHeader) {

        HeadView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"head" forIndexPath:indexPath];

        headerView.imageView.image=[UIImage imageNamed:@"xxx"];

        return headerView;

    }

    FootView * footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"foot" forIndexPath:indexPath];

    footerView.imageView.image=[UIImage imageNamed:@"xxx"];

    return footerView;

}

...........................................................

用xib來實現方法如下: 

//注冊headerView Nib的view需要繼承UICollectionReusableView

    [self.collectionView registerNib:[UINib nibWithNibName:@"xxx" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];

//注冊footerView Nib的view需要繼承UICollectionReusableView

    [self.collectionView registerNib:[UINib nibWithNibName:@"xxx" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"foot"];

實現方法

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

{    

    NSString * reuseIdentifier;

    if ([kind isEqualToString: UICollectionElementKindSectionFooter ]){

        reuseIdentifier = @"foot";

    }else{

        reuseIdentifier = @"head";

    }

   

    UICollectionReusableView *view =  [collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:reuseIdentifier   forIndexPath:indexPath];

    //控件綁定tag

    UILabel *label = (UILabel *)[view viewWithTag:1];

    if ([kind isEqualToString:UICollectionElementKindSectionHeader]){

        label.text = [NSString stringWithFormat:@"這是header:%ld",(long)indexPath.section];

    }

    else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){

        view.backgroundColor = [UIColor lightGrayColor];

        label.text = [NSString stringWithFormat:@"這是footer:%ld",(long)indexPath.section];

    }

    return view;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM