IOS开发之集合视图中的可重用对象

       前面我们讲到了表视图的可重用对象,没多大印象的朋友可查看该文《IOS开发之表视图的可重用对象》再温习一遍。今天,南昌APP开发公司主要为大家介绍一下IOS开发中集合视图中的可重用对象。

       集合视图在iOS 6之后才可以使用,它也有两种子视图采用可重用对象设计,它们是单元格视图和补充视图,这两个视图都继承自UICollectionReusableView,使用时需要自己编写相关代码。

       1、单元格视图

       在集合视图中,我们可以使用UICollectionView的dequeueReusableCellWithReuseIdentifier:forIndexPath:方法获得可重用的单元格,模式代码如下:

       override func collectionView(collectionView: UICollectionView,

        cellForItemAtIndexPathindexPath: NSIndexPath) ->

        UICollectionViewCell {

        var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell",

        forIndexPath: indexPath) as Cell

        ......

        return cell

       }        

       - (UICollectionViewCell *)collectionView:(UICollectionView *)

        collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

       {

        Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:

        @"CellIdentifier" forIndexPath:indexPath];

        ......

        return cell;

       }

       在上述代码中,collectionView:cellForItemAtIndexPath:方法是集合视图的数据源方法,其中Cell是我们自定义的继承自UICollectionReusableView的单元格类。使用dequeueReusableCellWithReuseIdentifier:时,需要使用故事板设计UI,并且需要将单元格的Identifier属性设置为Cell(如图1所示)。

图1、设定集合视图单元格的属性

       2、补充视图

       集合视图单元格可以使用UICollectionView的dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:方法获得可重用的补充视图,模式代码如下:

       override func collectionView(collectionView: UICollectionView,

        viewForSupplementaryElementOfKind kind: String,

        atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

        var headerView: UICollectionReusableView = collectionView.

        dequeueReusableSupplementaryViewOfKind

        (UICollectionElementKindSectionHeader,

        withReuseIdentifier : "HeaderIdentifier", forIndexPath:indexPath)

        as UICollectionReusableView

        ......

        return headerView

       } 

       - (UICollectionReusableView *)collectionView:(UICollectionView

        *)collectionView

        viewForSupplementaryElementOfKind:(NSString *)kind

        atIndexPath: (NSIndexPath *)indexPath

       {

        HeaderView *headerView = [collectionView

        dequeueReusableSupplementaryViewOfKind:

        UICollectionElementKindSectionHeader

        withReuseIdentifier:@"HeaderIdentifier" forIndexPath:indexPath];

        headerView.headerLabel.text = [self.eventDate objectAtIndex:indexPath.section];

        return headerView;

       }

       collectionView:viewForSupplementaryElementOfKind:atIndexPath:方法是集合视图的数据源方法,其中HeaderView是我们自定义的继承自UICollectionReusableView的补充视图类。使用dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:时,需要使用故事板设计UI,并将补充视图的Identifier属性设置为HeaderIdentifier,如图2所示。

图2、设定补充视图的属性

提供全面的搜索引擎优化学习交流,专注网站优化和搜索引擎营销推广服务。用专业的SEO技术为企业网站提升关键词排名,让你的网站不仅满足用户体验还要适合搜索引擎优化规则。
易速网站优化公司 » IOS开发之集合视图中的可重用对象
享更多特权,立即登录下载海量资源
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡