[iOS]自定义UICollectionView 1--CollectionItem的实现

在iOS6.0以后的版本中水果加入了UICollectionView控件,可是UICollection并不支持iOS6.0以前的版本。要实现UICollectionView能够有许多方法:可使用UITableView,经过自定义UITableViewCell来实现相似UICollectionView的布局样式,也能够经过彻底重写UITableView来从新实现一遍(有点从新造轮子的嫌疑)。ide

这里咱们选择后面一种方法来实现,这样能够充分的理解UITableview的重用机制以及其具体实现方式。首先在编码以前咱们应该清楚咱们须要什么:一个Collection容器与用来展现内容的CollectionItem。这时最基本的,因为在项目中须要用到上拉更多、下拉刷新以及headerView的功能因此还须要更多、刷新的View,在以后的计算过程当中也须要考虑到headerView。布局

首先建立CollectionItem编码

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface iCollectionItem : UIView
@property (strong,nonatomic) UIImageView *backgroundImage;
@property (strong,nonatomic) NSString *reuseIdentifier;
@property (assign,nonatomic) CGPoint point;
@property (strong,nonatomic) NSString *itemIdentifier;
-(id)initWithReuseIdentifier:(NSString *)identifier;
-(void)itemTaped;
-(void)reset;
@end

在Item的头文件中定义了背景ImageView、重用标志、用来指示位置的point属性,初始化事件、点击事件、重置方法、两个Item对比的方法。 在实现文件中首先引入须要的头文件。atom

#import "iCollectionItem.h"
#import "iCollectionView.h"
@interface iCollectionItem()
@property(strong,nonatomic) UITapGestureRecognizer *tapGR;
@end

初始化方法中对item进行初始化code

-(id)initWithReuseIdentifier:(NSString *)identifier{
    self=[super init];
    if (self) {
        _reuseIdentifier=identifier;
        [self setUserInteractionEnabled:YES];
        _backgroundImage= [[UIImageView alloc] init];
        _tapGR=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(itemTaped)];
    }
    return self;
}

而后重写setFrame方法:事件

-(void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    [_backgroundImage setFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    _backgroundImage.tag=10099;
}

这样使得item在改变大小时背景可以同样进行变化。接下来重写layoutSubviews方法get

-(void)layoutSubviews {
    [super layoutSubviews];
    if([self viewWithTag:10099]== nil)   {
        [self addSubview:_backgroundImage];
        [self sendSubviewToBack:_backgroundImage];
    }
    [self addGestureRecognizer:_tapGR];
}

点击事件的实现经过手势来实现:it

-(void)itemTaped{
    [(iCollectionView *)[self superview] itemClickedAtPoint:self.point];
}

以后是能够由子类重写的方法io

#pragma mark -
#pragma mark override
-(void)reset{
}
相关文章
相关标签/搜索