`
dcj3sjt126com
  • 浏览: 1861021 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

怎样在UICollectionView中添加Header和footer

    博客分类:
  • IOS
阅读更多

转自:http://my.oschina.net/u/723760/blog/221525

翻译自:http://www.appcoda.com/supplementary-view-uicollectionview-flow-layout/

 

    在前面我们已经学过,每个collection view都必须有数据源为其提供内容。它的责任是为collection views完成以下的事情:

  • 控制collection view的section数目

  • 每个section中的item的个数

  • 为特定的数据项提供cell view

         显然,简单的Recipe app,我们在前面的教程中包含了其中一个部分,在这里我们将继续讲讲collection view并且告诉你如何利用不同的section组织items,你将会学到怎样为collection view添加header视图和footer视图。

       如果你没有看过前面的教程,建议你去看一看前面的教程,或者你可以到这里下载here

 

 Split Recipes into Two Sections in UICollectionView

          在这个简单的程序中,RecipeCollectionViewController是集合视图的数据源对象,为了把视图分成两个部分,我们需要有一些变化,接下来我们完成:

           起先,recipeImages数组是存储所有recipes的名称,因为我们想把recipes分成两组,我们要修改我们的代码,并使用签到数组来存储不同的recipe,也许你还不明白啥是嵌入的数组,下面的图片会让你明白的。第一组包含主要的图像,而另一个为drink和dessert。顶级数组(即recipeImages)包含两个数组,每个数组部分的特定区域包含特定的data items。

Nested Array Explained

           让我们开始编写代码,在RecipeCollectionViewController.m中初始化"recipeImages"数组,并在viewDidload方法中写下面的方法:

        - (void)viewDidLoad

    {

              [super viewDidLoad];

            //Initialize recipe image array

           NSArray *mainDishImages = [NSArray arrryWithObjects:@"egg_benedict.jpg"@"full_breakfast.jpg"@"ham_and_cheese_panini.jpg"@"ham_and_egg_sandwich.jpg"@"hamburger.jpg"@"instant_noodle_with_egg.jpg"@"japanese_noodle_with_pork.jpg"@"mushroom_risotto.jpg"@"noodle_with_bbq_pork.jpg"@"thai_shrimp_cake.jpg"@"vegetable_curry.jpg"nil];

             NSArray *drinkDessertImages = [NSArray arrayWithObjects:@"angry_birds_cake.jpg"@"creme_brelee.jpg"@"green_tea.jpg"@"starbucks_coffee.jpg"@"white_chocolate_donut.jpg"nil];

      recipeImages = [NSArray arrayWithObjects:mainDishImages,drinkDesserImages,nil];

    }

          上面的代码将recipes images分成两组。接下来,修改"numberOfIntemsInSecion:"方法来返回,每个secions中的items数目:

        - (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSecion:(NSInteger)section

   {

             return [[recipeImages objectAtIndex:sectin]count];

   }

              接下来我们按照下面的方法修改"cellForItemAtIndexPath:"方法

       - (UICollectionVIewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

              static NSString *identifier = @"Cell";

              RecipeViewCell *cell = (RecipeViewCell *)[collectionView dequeueReuseIdentifier:identifier forIndexPath:indexPath];

             UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];

             recipeImageView.image = [UIImage imagedNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];

             cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame-2.png"]];

                  return cell;

}

        你可以和以前的代码比较以下,你就会知道只有一样是唯一的变化。我们首先检索该数组的section number然后从section中获取具体的items。

         最后,怎样给collection view实现两个section,这个可以通过方法调用下面的方法来完成即:在RecipeCollectionViewController.m中的numberOfSectionsInCollectionView方法,在collectin View中返回section中的数量。

  - (NSInteger)numberOfSectionsInCollectionVIew:(UICollectionView *)collectionView

{

    return [recipeImages count];

}

现在运行你的app,你会在屏幕上看到下面的显示

Recipe App with Two Sections

Tweak the Margin of Your Content using Section Insets

 (利用Section Insets)

   程序是完成了,但是你是否觉得看起来并不怎么顺眼呢?图像的第一部分的最后一行和第二部分的第一样靠的太近。我们可以使用插入图到内容周围的空间中来改变一些格局,通过下图你可以比较直观 的看到影响:

Add margin using section insets

    你可以利用UIEdgeInsetsMake来完成插入:

               insert = UIEdgeInsetsMake(top,left,botton,right);

    在我们的Recipe app中我们只能在两个section之间添加空间。在RecipeCollectionViewController.m文件中的ViewDidLoad方法中,添加下面的方法:

          UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout *)self.collectionViewFlowLayout;

          collectionViewLayout.sectionInset = UIEdegeInsetsMake(20,0,0,0);

 上面的代码实现了在collection view中创建和添加插入。现在我们运行程序,你将会看到下面的 图像显示,我们在两个section之间增加了一些空间。

      

Recipe Collection View with Insets

 

      添加头部和底部视图

             现在我们进一步调整应用程序,让其更酷。让我们来给应用程序添加头部和底部视图,我们利用UICollectionViewFlowLayout来实现这一点。这里的header和footer视图可以被称为流布局的补充。在默认情况下,这些视图是在流布局中禁用的。但可以通过下面几件事情来配置header和footer视图:

  1.   为了尽量保持简单,所以我们可以选择storyboard来实现(当然这不是必须的,你同样可以使用代码来实现这一点)

  2. 实现 UICollectionViewDataSource协议的 collectionView:viewForSupplementaryElementOfKind 方法,并通过这个方法来实现补充试图在collection view中显示。

 

       在Storyboard中设计Header和Footer

       首先download the header/footer background images并且添加到Xcode工程中。

         到Storyboard中,选择collection view controller中的"Collection View"。在Attributes inspector中,选择"Section Header"和"Section Footer",一旦选中你就会在屏幕中看到下面的的显示:

Storyboard Enables Section Header and Footer

       在header和footer之间默认为空,我们会用storyboard来设计视图。header view是专门用来显示一个部分的标题,而底部视图只显示静态横幅图片。利用storyboard,从对象库中拖出image view并在其上面添加一个标签。设置字体颜色为白色,底部视图只需添加一个image view。如图:

Design header and footer views

   选中footer view中的image view,在Attributes inspector中命名背景图片为"footer_banner.png"

Add Footer View Background

       最重要的是,我们必须为header和footer view指定一个标识符。这个标示符将会被用于代码识别图片名称。在Atteributes inspector中设置header view的identifier为“HeaderView”,同样的把footer view的identifier设置为“FooterView”。

      

Collection Reusable View Header Identifier

 

为Header View添加新类

    在默认情况下,header和footer view和UICollectionResuable类相关联。为了在header view中显示我们需要的背景和标题,我们必须创建一个新的继承自UICollectionResuableView的类,我们可以命名为RecipeCollectionHeaderView。

Add Collection Header View Class

  在storyboard的Identifier inspector中的sustom class设置为“RecipeCollectionHeaderView”。按住Ctrl键,单机header中的image view,并拖向RecipeCollectionHeaderView.h中插入一个Outlet 变量。命名变量为"backgroundImage"。重复同样的步骤对UILabel实现,然后命名为"title"。

   

Establish connection with RecipeCollectionHeaderVeiw

     实现viewForSupplementaryElementOfKind方法

            如果你尝试运行应用程序,你可能不会看到header和footer,这是因为我们还没有实现"viewFOrSupplementaryElementOfKind:"方法。选择“RecipeCollectionViewController”,并添加import语句。

              #import "RecipeCollectionHeaderView.h"

 下面就是实现viewforSupplementaryElementOfKind方法的代码:

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

{

      UICollectionReusableView *reusableview = nil;

     if (kind == UICollectionElementKindSectionHeader){

         RecipeCollectionHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];

         NSString *title = [[NSString alloc] initWithFormat:@"Recipe Group #%i",indexPath.section +1];

         headerView.title.text = title;

         UIImage *headerImage = [UIImage imageNamed:@"header_banner.png"];

         headerView.backgroundImage.image = headerImage;

         reusableView = headerView;

  }

        if (kind == UICollectionElementKindSectionFooter){

    UICollectionReusableView *footerview = [collectionView dequeueResuableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath];

       reusableview = footerview;

}

   return reusableview;

   

}

上面的代码告诉它页眉/页脚视图应该在每个部分中使用collect view。我们首先确定该集合视图要求header或footer view。这可以通过使用一种变量来完成。对于头来看,我们出列header view(使用dequeueReusableSupplementaryViewOfKind :方法),并设置适当的标题和图像。正如你可以从两个if之间的代码,我们使用我们之前分配给获得header/footer view标识符。

 现在运行代码,我们可以看到运行的结果:

   

 

Recipe App with Header and Footer

分享到:
评论

相关推荐

    iOS UICollectionView 纯代码布局,添加Section Header 头部视图跟 Section Footer尾部视图

    在这个主题中,我们将深入探讨如何通过纯代码方式设置UICollectionView的布局,并添加Section Header和Footer视图。 首先,你需要创建一个UICollectionView类的实例,然后配置其frame和数据源代理。数据源代理...

    ios-自定义瀑布流(可添加自定义header和footer).zip

    2. **HeaderFooterView.swift**:这个文件可能包含了自定义头部和尾部视图的实现。开发者可以通过这个类来自定义显示在瀑布流顶部和底部的视图,例如广告、推荐信息或者加载更多的按钮。 3. **WaterfallFlowLayout....

    swift-自定义瀑布流可添加自定义header和footer

    在UICollectionView中,可以使用`register(_:forSupplementaryViewOfKind:withReuseIdentifier:)`方法注册header和footer视图,并在`collectionView(_:viewForSupplementaryElementOfKind:at:)`代理方法中返回对应的...

    UICollectionView复用

    在处理大量数据时,为了提高性能并减少内存消耗,UICollectionView利用了复用机制,这一机制同样适用于header、footer和Cell。下面将详细阐述UICollectionView的复用原理以及如何在实践中应用。 一、...

    UICollectionView详解并解决MJRefresh下拉刷新遮挡问题

    以上内容涵盖了UICollectionView的基本使用、添加header视图以及解决MJRefresh下拉刷新遮挡问题的方法。通过理解这些知识点,开发者能够更好地掌握UICollectionView的使用,为用户提供更加丰富和个性化的界面体验。...

    IOS UICollectionView布局详解

    在实际应用中,UICollectionView的强大之处还在于它可以处理头部和尾部视图(header and footer views)、可变大小的cell、以及复杂的交互效果。例如,你可以通过实现`collectionView(_:...

    支持下拉刷新,上拉加载,Header,Footer,复杂多种数据结构类型.zip

    标题和描述中提到的"支持下拉刷新,上拉加载,Header,Footer,复杂多种数据结构类型",这些都是移动应用开发中的关键特性,主要应用于列表视图或者网格视图等展示大量数据的场景。以下是对这些概念的详细解释: 1....

    UICollectionView-基础布局篇.zip

    9. **Header和Footer**:类似于UITableView,UICollectionView也可以有header和footer视图,通过`viewForSupplementaryElementOfKind:atIndexPath:`方法进行定制。 10. **动画效果**:利用`performBatchUpdates(_:...

    CollectionView header悬停

    在这个文件中,开发者会定义header的外观和交互,可能包括UI设计、添加手势识别等。 通过自定义UICollectionViewFlowLayout和相应的视图控制器逻辑,开发者可以实现类似“CollectionView header悬停”的功能,为...

    UICollectionView使用的demo

    - 头部和尾部视图:`supplementaryViewOfKind(_:withReuseIdentifier:for:)`可以添加header和footer view。 - 嵌套滚动:在UICollectionView中嵌套另一个UICollectionView或UIScrollView,实现复杂的布局效果。 -...

    集合视图UICollectionView 表格 布局 iOS

    UICollectionView 还支持诸如 header 和 footer、drag and drop、infinite scrolling 等高级特性。可以根据需求选择实现。 综上所述,UICollectionView 在 iOS 开发中是创建表格布局的强大工具,提供了丰富的自定义...

    UICollectionView

    在UICollectionViewFlowLayout中,你可以设置header和footer的大小,它们会在每个section的开始或结束处显示。 最后,别忘了注册cell和header/footer的类或nib,以便collectionView知道如何创建这些视图。注册可以...

    UICollectionView-Demo

    - 补充视图(Supplementary Views):像头视图(Header)和尾视图(Footer)一样,可以在UICollectionView中添加。 - 注册单元格和补充视图:可以使用`register(_:forCellWithReuseIdentifier:)`和`register(_:...

    swift学习控件篇:UICollectionView

    1. 在Storyboard中添加UICollectionView:通过拖拽并设置约束来创建,也可以代码创建并设置frame。 2. 设置CollectionView的数据源和代理:需要遵循UICollectionViewDataSource和UICollectionViewDelegate协议,通常...

    swift-iOSHeaderFooter切换出现组件

    它可能包括自定义的HeaderFooterView子类,以及在ViewController中进行布局和逻辑控制的部分。 总的来说,Swift-iOSHeaderFooter切换出现组件展示了如何利用Swift的灵活性和iOS SDK的强大功能,创建出富有创新性的...

    ios-UICollectionView的使用,详解.zip

    - 在Storyboard中添加UICollectionView,并设置约束以确定其大小和位置。 - 配置UICollectionViewDataSource和UICollectionViewDelegate,通常这两个角色由同一个UIViewController实现。 - 设置...

    ios-UICollectionView demo.zip

    在iOS开发中,UICollectionView是一个非常重要的视图组件,它允许我们以网格布局或者自定义布局显示大量的数据。这个"ios-UICollectionView demo.zip"文件提供了一个示例,展示了如何使用UICollectionView来创建一个...

    iOS UIcollectionView

    1. 创建UICollectionView实例:在Storyboard中添加UICollectionView,或者在代码中创建并添加到父视图。 2. 设置DataSource和Delegate:确保你的ViewController实现了UICollectionViewDataSource和...

Global site tag (gtag.js) - Google Analytics