您的位置:首页 > 产品设计 > UI/UE

iOS之UITableView之样板代码

2013-11-06 23:32 387 查看
初次写博文,写的不好,呵呵,见谅......

做了很久的iOS了,大家都知道,在iOS里面用的最多的UI控键是什么?那就是UITableVIew,现在任何一个应用都不可能没有这个控键,但是大家没有觉得很这个控键的内部实现代码很繁琐么?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
return cell;
}


每次实现UITableView里面的代码都很繁琐,特别是在高度自定义UITableViewCell的时候

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString  *CellIdentifier = @"cell";
ZJHomeCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ZJHomeCustomCell alloc] initWithNbName:@"ZJHomeCustomCell"] ;
}


不管大家觉不觉得,反正我觉得是,工作学习之余,自己写了一个关于UITableViewCell的smart样板代码。不废话,上代码

首先自定义一个类,继承UITableViewCell

ZJSmartTableVIewCell.h

@interface ZJSmartTableViewCell : UITableViewCell

+(id)cellForTableViewWithIdentifer:(UITableView*)tableView;
+(NSString*)identifier;
- (id)initWithIdentifier:(NSString*)cellID;
@end

ZJSmartTableVIewCell.m

#pragma mark 返回Cell对象,初始化都在里面完成
+(id)cellForTableViewWithIdentifer:(UITableView*)tableView;
{
NSString * cellID = [self identifier];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[self alloc] initWithIdentifier:cellID];
}
return cell;
}
#pragma mark 返回当前类名字符串,也就是Cell重用卫衣标示符
+(NSString*)identifier
{
return NSStringFromClass([self class]);
}
#pragma mark 这个方法是用户自定义方法,自己在这个方法里面自定义布局等等
- (id)initWithIdentifier:(NSString*)cellID
{
return [self initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}


样板代码写好了,那么我们就用一用吧,首先我们创建一个类,继承 ZJSmartTabelViewCell

#import "ZJSmartTableViewCell.h"
@interface ZJCustom : ZJSmartTableViewCell

//自定义布局的成员变量
@property (nonatomic,retain) UILabel *customLabel;
@end

#import "ZJCustom.h"

@implementation ZJCustom

//如果需要自定义Cell,那么就重写这个方法吧
//- (id)initWithIdentifier:(NSString*)cellID
//{
//    self = [super initWithIdentifier:cellID];
//    if (self) {
//        _customLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 80)];
//        _customLabel.backgroundColor = [UIColor orangeColor];
//        [self.contentView addSubview:_customLabel];
//    }
//    return self;
//}
@end


最后呢,既然 样板代码和自定义的Cell都写好了,那么我们就来用用吧

在UITableView的回调里面,我们只需要实例话ZJCustom就可以了,看见没有,一行代码搞定

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ZJCustom *cell = [ZJCustom cellForTableViewWithIdentifer:tableView];
cell.textLabel.text = @"Test";
return cell;
}


思路,就是把判断Cell的繁琐的代码抽出来到Cell的超类里面,自己来判断重用这块,这样抽取出来以后,那么,以后我们再就节省代码了。

这是代码书写的方法,如果用IB布局的话,方法也是一样的,这里就不写出来了,我想要是大家看了,也可以试一试自己封装一下.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息